在追加一个.txt的每一行文件使用Python的特定字符串 [英] Append in each line of a .txt file a specific string using Python
本文介绍了在追加一个.txt的每一行文件使用Python的特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有以下格式的.txt文件:
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.
推荐答案
您可以使用应用re.sub功能。
You could use re.sub function.
要追加在每行的开始。
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))
这篇关于在追加一个.txt的每一行文件使用Python的特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文