在固定文本后替换可变文本

2024-05-28 23:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个.txt文件,看起来像这样:

Patient Name         : John Don, 9989
Patient ID           : 9989
Comment              : Summation
Date                 : 09.08.2017
Exported by          : Denver
Type                 : DVH
Description          : Some random text

我还有另外一个名单,上面有我想用的名字

因此,基本上,我在不同的文件夹中有几个这样的.txt文件,它们的名称与我在列表中的名称相同,fx:

name_list = ["1", "1_NEW", "2", "3", "3_RE"]

我想做的是将Patient namePatient ID的值更改为列表中的任何值

例如,对于列表中的第一个元素,它打开同名文件夹,然后打开该文件夹中的.txt文件(始终同名),读取.txt文件,并将Patient namePatient ID后面的值更改为列表的值。因此,对于第一个问题,我将以:

Patient Name         : 1
Patient ID           : 1
Comment              : Summation
Date                 : 09.08.2017
Exported by          : Denver
Type                 : DVH
Description          : Some random text

这能做到吗


Tags: 文件nametxt文件夹id列表dateby
1条回答
网友
1楼 · 发布于 2024-05-28 23:23:34

公平地说,下面是一个您可以使用的代码示例:

Be warned though as this could overwrite files (try with one file)

for file in ["1"]:

    # Read file
    with open("{0}/{0}.txt".format(file)) as f:
        filecontent = [i.strip("\n") for i in f.readlines()]    

    # Update first and second row
    filecontent[0] = filecontent[0].split(":")[0] + ": {}".format(file)
    filecontent[1] = filecontent[1].split(":")[0] + ": {}".format(file)

    # Ovewrite old file and write
    with open("{0}/{0}.txt".format(file), "w") as f:
        string = '\n'.join(filecontent)
        f.write(string)
        # print(string)

相关问题 更多 >

    热门问题