tags:

views:

86

answers:

3
for line in file:
    print line

In the code above when I change it to:

for line in file:
    print line + " just a string"

This only appends "just a string" to the last line

PS: Python newbie

+3  A: 

Iterating over a file includes the line endings, so just remove them:

for line in file:
  print line.rstrip("\n"), "something"

Note that print will append its own newline, so even without appending "something" you'd want to do this (or use sys.stdout.write instead of print). You may also use line.rstrip() if you want to remove all trailing whitespace (e.g. spaces and tabs too).

Documentation:

Files support the iterator protocol. Each iteration returns the same result as file.readline(), and iteration ends when the readline() method returns an empty string.

Roger Pate
Thanks, your answer was useful, there was some problem in the text file (as I copied from web page -> excel -> text file) so it was appending to the last line but definitely I needed rstrip() ;)
Vishal
A: 

The line received through the iterator includes the newline character at the end - so if you want "something" to be appended on the same line you will need to cut this off.

for line in file:
    print line[:-1] + " something"
thrope
This breaks on the last line of the file, if it doesn't have a newline, by removing data.
Roger Pate
A: 

This is how you can append 'something' at the end of each line:

import fileinput

for line in fileinput.input("dat.txt"):
    print line.rstrip(), ' something'

If you want to append 'something' to line and then print the line:

import fileinput

for line in fileinput.input("dat.txt"):
    line = line.rstrip() + ' something'
    print line
    # now you can continue processing line with something appended to it

dat.txt file:

> cat dat.txt
one
two and three
four -
five
.

output:

> ./r.py
one  something
two and three  something
four -  something
five  something
.  something
stefanB
I want to append string "something" to the line and print.
Vishal