How to add a string to each line in a file?

python, string

Solution

Remember, using the `+` operator to compose strings is slow. Join lists instead.

file_name = "testlorem"
string_to_add = "added"

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) 

Problem

I need to open a text file and then add a string to the end of each line. So far: ``` appendlist = open(sys.argv[1], "r").read() ```

Original source