使用 Python 在 .txt 文件的每一行中追加一个特定的字符串
Append in each line of a .txt file a specific string using Python
我有一个 .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")
但我只写在文件的末尾。
您可以使用 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))
您可以尝试这样做:
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)
我有一个 .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")
但我只写在文件的末尾。
您可以使用 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))
您可以尝试这样做:
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)