1

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.

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

4 Comments

I tried it and it writes in front of the already existing text in the corresponding line. How can it write at the end of it?
you the one asks for appending at the start of each line.
oops yes. I thought it was obvious from the example folders i posted but anyway I edited my post since it was not clear. How can i do it after the end of the line anyhow?
even with the rstrip('\n') it writes at the beginning
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.