user3436288
user3436288

Reputation: 53

read a file line by line and append word

I am a newbie to python and trying to read file line by line and append a word at the end of each line. The "print line" shows that the required word has got appended but the same thing not written back to the file as required . Appreciate your help.

#!/usr/bin/python
f=open('test1', 'r+')
for line in f:
    line=line.strip("\n")
    line=line +" " + 'test2'
    print line
    f.write(line)
f.close()

Upvotes: 1

Views: 3254

Answers (4)

ystan-
ystan-

Reputation: 1536

mgilson's code is slightly wrong. Corrected:

with open("test1", "r") as f:
    new_contents = [line.strip() + "test2" for line in f.readlines()]
with open("test1", "w") as f:
    f.write("\n".join(new_contents))

Upvotes: 1

user1715791
user1715791

Reputation: 11

The code given by mgilson is great! However, the function you request is not possible if you read and append at the same time.

I am too new to python. So, I find myself more comfort in the following syntax.

# read in 
f = open('test1', 'r')
newlines = []
for line in f:
    newline = line.strip("\n") + " " + 'test2' + "\n"
    newlines.append(newline)
    print newline,
f.close()
# overwrite the same file
f = open('test1', 'w')
f.writelines(newlines)
f.close()

Upvotes: 1

mgilson
mgilson

Reputation: 309881

Generally speaking, reading/writing a file at the same time is a really horribly difficult thing to get right. Usually, you'll read from one file and write to a different file (possibly in memory). An in-memory implementation would be something like:

with open('test1', 'r') as fin:
    lines = [line.strip('\n') + ' test2\n' for line in fin]
with open('test1', 'w') as fout:
    fout.writelines(lines)

Notice that I read all the file's data into memory in the first with block. In the second with block, I write all that data back out to a new file (which conveniently has the same name as the old file effectively overwriting the old). Of course, if memory is a problem, you can read a line and then write a line to a new file (with a different name). After you've closed and flushed both files, then you can use shutil.move to rename the new file so that you overwrite the old one.

Upvotes: 1

zbtong
zbtong

Reputation: 319

@mgilson's answer is very well, and just a little error is the lines in the end of lines = [line.strip('\n') + ' test2\n' for line in lines] should be fin.

Upvotes: 1

Related Questions