Friday, September 21, 2007

Chop, chomp, whatever

I think this is a fairly pythonic way to import a text file and delete all the newlines. It appears to work regardless of the newline style, and it's way better than the way that I used to do it. Here you go:

stuff = []
fp = open('input.txt','rU')
stuff = (fp.read()).splitlines(0)
print stuff
The key is the argument to the string.splitlines method. If you set the argument to 0, it removes the newlines. If set to 1, newlines are preserved. The default is 0, so splitlines() will discard the newline characters.

Here is the way I used to do it. It is not correct:
stuff = []http://www.blogger.com/img/gl.link.gif
fp = open('input.txt','rU')
stuff = fp.readlines()
for i in len(stuff):
# trim one character off the end of the line. NOT GOOD.
# It usually works for me, because I'm working with Unix-style
# line endings. Won't work if you're on DOS/Windows.
stuff[i] = stuff[i][:-1]
print stuff
I discovered 'splitlines' in Brad Dayley's "Python Phrasebook". For a review of all of Python's string methods, see this page:

http://docs.python.org/lib/string-methods.html

No comments: