简体   繁体   English

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

[英]Append in each line of a .txt file a specific string using Python

I have a .txt file with has the following format: 我有一个.txt文件,其格式如下:

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

I want to append in the end of each line another folder path in order to make it look like this: 我想在每行的末尾附加另一个文件夹路径,以使其看起来像这样:

/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

Till now I have tried in a loop: 到目前为止,我已经尝试过一个循环:

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

But i only writes at the end of the file. 但是我只写在文件的末尾。

You could use re.sub function. 您可以使用re.sub函数。

To append at the start of each line. 在每行的开头附加。

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))

To append at the end of each line. 在每行末尾附加。

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))

You can try to do something like this: 您可以尝试执行以下操作:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM