Personal tools
You are here: Home CDAT Tips and Tricks Python Tips File input and output.
Document Actions

File input and output.

by Renata McCoy last modified 2007-05-08 10:44

Goal: Learn about file input and output in python.

 
To open a text file and read its contents you would:
# Get a file object
f = open("myfile.txt")

# The readline() method is invoked on file
# and one line is read from the file.
line = f.readline()

# The following section keeps printing and reading
# subsequent lines of data while there are new lines to
# be read
while line:
print line
line = f.readline()

# The while loop is exited when there are no more lines
# to be read. To close the open file:
f.close()
To write output to a file:
fout = open("out.txt", 'w')
# The `w' indicates file should be opened for writing
# and is created if it does not already exist.

fout.write("hello\n")
# or equivalently
print >> fout, "hello"

fout.close()


Powered by Plone