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