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

混江龙づ霸主 提交于 2019-12-24 07:14:36

问题


I have a .txt file with has the following format:

/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.


回答1:


You could use re.sub function.

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



回答2:


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)


来源:https://stackoverflow.com/questions/28855043/append-in-each-line-of-a-txt-file-a-specific-string-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!