对不起,我的英语不好

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相关问答推荐

Django注释:将时差转换为小数或小数

telegram 机器人API setMyName不起作用

Plotly:如何更改Heatmap中彩色条的勾选文本

自定义新元未更新参数

"如果发生特定错误,返回值

"Discord机器人中缺少所需的位置参数ctx

使用matplotlib pcolormesh,如何停止从一行绘制的磁贴连接到上下行?

剧作家Python:expect(locator).to_be_visible()vs locator.wait_for()

Python中MongoDB的BSON时间戳

Class_weight参数不影响RandomForestClassifier不平衡数据集中的结果

如何在msgraph.GraphServiceClient上进行身份验证?

Python中的嵌套Ruby哈希

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

Python—从np.array中 Select 复杂的列子集

为什么抓取的HTML与浏览器判断的元素不同?

Python+线程\TrocessPoolExecutor

实现神经网络代码时的TypeError

如何更新pandas DataFrame上列标题的de值?

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

Numpyro AR(1)均值切换模型抽样不一致性