Open and reading a file...
Robin Munn
rmunn at pobox.com
Thu Nov 14 17:43:36 EST 2002
Marlon Rea <mrea at commerceworks.on.ca> wrote:
> Can someone help me with opening and reading a file???? THANK YOU ALL
The most common operations:
file_object = file('somefile.txt', 'r') # 'r' for read, 'w' for write
file_object = open('somefile.txt', 'r') # In Python 2.1 or earlier
buf = file_object.read() # Slurp the whole file at once. OR...
lines = file_object.readlines() # Split whole file into lines. OR...
for line in file_object.xreadlines(): # Only one line at a time. OR...
do_something_with(line)
for line in file: # Same as above, Python 2.2 and greater
do_something_with(line)
More information on file objects:
http://www.python.org/doc/current/lib/bltin-file-objects.html
Let us know if you have any more questions that this answer didn't cover.
--
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838
More information about the Python-list
mailing list