简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM