UPDATE 2 (November 2017)
Sorry for not having updated this in so many years. 2004 was a different Peter and I'm sorry if people landed on this blog post and got the wrong idea.
To read lines from a file do this:
with open('somefile.txt') as f:
for line in f:
print(line)
This works universally in Python 2 and Python 3. It reads one line at a time by iterating till it finds line breaks.
readline()
and readlines()
. The answer is in the name. readline()
reads one readlines()
reads in the whole file at once and splits it by line.
These would then be equivalent:
f = open('somefile.txt','r')
for line in f.readlines():
print line
f.close()
# ...and...
f = open('somefile.txt','r')
for line in f.read().split('\n'):
print line
f.close()
The xreadlines()
function should be used for big files:
f = open('HUGE.log','r'):
for line in f.xreadlines():
print line
f.close()
Truncated! Read the rest by clicking the link below.
Python UnZipped
March 11, 2004
0 comments Python
Zipping and unzipping a file in Python is child-play. It can't get much easier than this. Well, in Windows you can highlight a couple of files and right-click and select from the WinZip menu. Here's how to do it in Python:
>>> import zipfile
>>> zip = zipfile.ZipFile('Python.zip', 'w')
>>> zip.write('file1.txt')
>>> zip.write('file2.gif')
>>> zip.close()
Still confused? Read this article for "Dev Shed"n:http://www.devshed.com/ then. The article includes some more advanced uses as well.