python - 如何替换 txt 文件中已存在的数据 --python

标签 python list

抱歉我的英语不好 我想为我的项目做一个编辑功能,但是我无法将编辑的内容保存到 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/

相关文章:

java - 如何将AbstrDoubleList的内容写入TextArea?

c# - 通过发送List<record>发送数据库

python - PySPark - 确定操作后数据类型的函数

python - 我如何告诉 pyparsing 丢弃部分已解析的字符串?

python - PyCharm 没有自动完成 AWS Glue Python

R 更改嵌套列表的类型

python - 使用 split() 时如何使标点符号成为一个单独的项目

python - 用另一个列表中的值替换列表中的特定值

python - 如何使用 argparse 在 python 脚本中通过管道发送参数?

python - 使用 Python 库的多元多重回归