抱歉我的英语不好 我想为我的项目做一个编辑功能,但是我无法将编辑的内容保存到 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
的特权,因为:So You Want To Write Your Own CSV code? .该代码使用名为 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()
关于python - 如何替换 txt 文件中已存在的数据 --python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72706257/