【问题标题】:Append in each line of a .txt file a specific string using Python使用 Python 在 .txt 文件的每一行中附加一个特定的字符串
【发布时间】:2015-05-05 11:25:27
【问题描述】:

我有一个 .txt 文件,格式如下:

/Users/my_user/folder1/myfile.dat
/Users/my_user/folder2/myfile.dat
/Users/my_user/folder3/myfile.dat
.
.
.
so on

我想在每一行的末尾附加另一个文件夹路径,使其看起来像这样:

/Users/my_user/folder1/myfile.dat,/Users/my_user/folder1/otherfile.dat
/Users/my_user/folder2/myfile.dat,/Users/my_user/folder1/otherfile.dat
/Users/my_user/folder3/myfile.dat,/Users/my_user/folder1/otherfile.dat
.
.
.
so on

到目前为止,我已经尝试过循环:

with open("test.txt", "a") as myfile:
    myfile.write("append text")

但我只写在文件的末尾。

【问题讨论】:

    标签: python file text append


    【解决方案1】:

    你可以使用 re.sub 函数。

    在每一行的开头追加。

    with open("test.txt", "r") as myfile:
        fil = myfile.read().rstrip('\n')
    with open("test.txt", "w") as f:
        f.write(re.sub(r'(?m)^', r'append text', fil))
    

    在每行末尾追加。

    with open("test.txt", "r") as myfile:
        fil = myfile.read().rstrip('\n')
    with open("test.txt", "w") as f:
        f.write(re.sub(r'(?m)$', r'append text', fil))
    

    【讨论】:

    • 我试过了,它写在对应行中已经存在的文本前面。结尾怎么写?
    • 你要求在每一行的开头附加。
    • 哎呀是的。我认为从我发布的示例文件夹中很明显,但无论如何我编辑了我的帖子,因为它不清楚。无论如何,我怎么能在行尾之后呢?
    • 即使是开头写的 rstrip('\n')
    【解决方案2】:

    你可以尝试做这样的事情:

    with open(file_name, 'r') as f:
        file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]
    
    with open(file_name, 'w') as f:
        f.writelines(file_lines)
    

    【讨论】:

      猜你喜欢
      • 2018-04-26
      • 2021-11-17
      • 2021-09-04
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多