使用Python在.txt文件的每一行附加一个特定的字符串

时间:2015-03-04 12:53:23

标签: python file text append

我的.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")

但我只在文件末尾写道。

2 个答案:

答案 0 :(得分:2)

您可以使用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))

答案 1 :(得分:0)

您可以尝试这样做:

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)