[英]How can i delete a couple lines of text that I inputted into a text file in python?
我正在 python 中制作一個簡單的小型密碼管理器。我具有創建一個帳戶的功能,該帳戶具有 3 個輸入、用戶名、密碼和網站。 我有一個 function 可以查看所有帳戶,其中顯示了所有信息所在的文件 info.txt 的內容。 我試圖創建一個 function 來刪除一個條目,但我不確定如何讓 function 刪除與用戶名關聯的所有信息行。 我想要一個輸入詢問“要刪除哪個帳戶”你輸入用戶名,它會刪除 info.txt 中與用戶名關聯的所有信息
代碼:
import os.path #Imports os module using path for file access
def checkExistence(): #Checking for existence of file
if os.path.exists("info.txt"):
pass #pass is used as a placeholder bc if no code is ran in an if statement and error comes.
else:
file = open("info.txt", "w") #creates file with name of info.txt and W for write access
file.close()
def appendNew():
#This function will append a new password in the txt file
file = open("info.txt", "a") #Open info.txt use a for appending IMPORTANT: opening a file with w for write will write over all existing data
userName = input("Enter username: ")
print(userName)
os.system('cls')
password = input("Enter password: ")
print(password)
os.system('cls')
website = input("Enter website: ")
print(website)
os.system('cls')
print()
print()
usrnm = "Username: " + userName + "\n" #Makes the variable usrnm have a value of "Username: {our username}" and a new line
pwd = "Password: " + password + "\n"
web = "Website: " + website + "\n"
file.write("----------------------------------\n")
file.write(usrnm)
file.write(pwd)
file.write(web)
file.write("----------------------------------\n")
file.write("\n")
file.close()
def readPasswords():
file = open("info.txt", "r") #Open info.txt with r for read
content = file.read() # Content is everything read from file variable (info.txt)
file.close()
print(content)
checkExistence()
while True:
choice = input("Do you want to: \n 1. Add account\n 2. View accounts\n 3. Delete account\n")
print(choice)
if choice == "1":
os.system('cls')
appendNew()
elif choice == "2":
os.system('cls')
readPasswords()
elif choice == "3":
os.system('cls')
else:
os.system('cls')
print("huh? thats not an input.. Try again.\n")
我嘗試通過刪除與用戶名匹配的行來刪除帳戶 function。 我唯一的問題是它只刪除了 info.txt 中帶有用戶名的行,但沒有刪除與該用戶名關聯的密碼和網站。
首先,您使用了錯誤的工具來解決問題。 pandas是一個不錯的嘗試庫,它使用.csv
文件(可以將其視為面向孔隙程序的 excel 文件)。 但是,如果您真的想使用基於文本文件的方法,您的解決方案將如下所示:
with open(textfile, 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
# The above makes a list of all lines in the file without \n char
index = lines.index(username)
# Find index of username in these lines
for i in range(5):
lines.pop(index)
# Delete the next five lines - check your 'appendNew' function
# you're using five lines to write each user's data
print(lines)
f.write("\n".join(lines))
# Finally, write the lines back with the '\n' char we removed in line 2
# Here is your readymade function:
def removeName(username):
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Function that also asks for username by itself
def removeName_2():
username = input("Enter username to remove:\t")
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Usage:
removeName(some_username_variable)
removeName_2()
同樣,這是一種相當笨拙且容易出錯的方法。 如果您更改了每個用戶詳細信息的存儲格式,則必須更改for
循環中刪除的行數。 嘗試 pandas 和 csv 文件,它們節省了大量時間。
如果您對這些感到不舒服或者您剛剛開始編碼,請嘗試 json 庫和.json
文件 - 在高層次上,它們是將數據存儲到文件中的簡單方法,並且可以使用json
庫在一個單行代碼。 您應該能夠在網上找到很多關於 pandas 和 json 的建議。
如果您無法理解 function 的作用,請嘗試閱讀try-except
塊和 function 參數(以及可能的全局變量)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.