开发者

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

for li开发者_StackOverflow社区ne 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


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.

  • http://docs.python.org/library/stdtypes.html#file.readline (quoted text is below the methods)


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"


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜