Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Add string to each line in a file

Tags:

python

string

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()
like image 933
Pcntl Avatar asked Nov 28 '13 19:11

Pcntl


Video Answer


2 Answers

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) 
like image 191
José Tomás Tocino Avatar answered Oct 08 '22 15:10

José Tomás Tocino


s = '123'
with open('out', 'w') as out_file:
    with open('in', 'r') as in_file:
        for line in in_file:
            out_file.write(line.rstrip('\n') + s + '\n')
like image 35
Guy Gavriely Avatar answered Oct 08 '22 15:10

Guy Gavriely