[英]How do I use a loop to check if the input already existed in the file in Python and append if it's new?
[英]How do I replace data that is already existed in txt file --python
對不起我的英語不好我想為我的項目做一個編輯功能但是我無法將編輯的內容保存到 txt 文件中。 有什么建議嗎?
def admin_edit_medic():
list_of_medicine = []
with open("medic.txt", "r") as medifile:
for line in medifile.readlines():
split = line.split(",")
list_of_medicine.append(split)
print(list_of_medicine)
print("\n"*2)
updated_details = []
data = str(input("Please input details to edit from the list: "))
edit = str(input("Please input new details to replace: "))
for medicine in list_of_medicine:
update = medicine.replace(data,edit)
updated_details.append(update)
print(list_of_medicine)
|txt file content|
Abacavir,20/5/2065,49.5,Treat HIV
Alemtuzumab,31/8/2045,977.9,Cure Leukhimia
下面的代碼應該可以解決問題。 我還獲得了不手動解析 CSV 文件medic.txt
的特權,因為: 所以您想編寫自己的 CSV 代碼? . 該代碼使用名為csv的標准 Python 模塊。
import csv
def admin_edit_medic():
list_of_medicine: list[str] = []
with open("medic.txt", "r") as medifile:
csv_reader = csv.reader(medifile)
for row in csv_reader:
list_of_medicine.append(row)
print(list_of_medicine)
print("\n"*2)
updated_details = []
data = str(input("Please input details to edit from the list: "))
edit = str(input("Please input new details to replace: "))
for row in list_of_medicine:
updated_row: list[str] = []
for item in row:
update = item.replace(data, edit)
updated_row += [update]
updated_details.append(updated_row)
print(list_of_medicine)
print(updated_details)
with open("medic.txt", "w") as medifile:
csv_writer = csv.writer(medifile)
for row in updated_details:
csv_writer.writerow(row)
if __name__ == '__main__':
admin_edit_medic()
在這里,您以只讀模式打開了一個文件。 要更改其內容,您需要以“w”模式打開它(將信息寫入文件)。 此外,您的代碼存在一些問題。 split
返回一個列表,因此您將無法將replace
方法用作medicine
對象。 為避免這種情況並正確寫入文件,請嘗試在函數末尾添加:
for medicine in list_of_medicine:
medicine = [edit if elem == data else elem for elem in medicine]
updated_details.append(medicine)
with open('medic.txt', 'w', encoding='utf-8') as new_file:
for line in updated_details:
line = ",".join(line)
new_file.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.