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.
解决方案
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))