Vishal
Vishal

Reputation: 20617

How to read line (from a file) and then append + print in python?

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

Upvotes: 1

Views: 3504

Answers (3)

stefanB
stefanB

Reputation: 79780

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

Upvotes: 0

Roger Pate
Roger Pate

Reputation:

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.

Upvotes: 5

robince
robince

Reputation: 10967

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"

Upvotes: 0

Related Questions