File input and output.
Goal: Learn about file input and output
in
python.
To open a text file and read its contents you would:
# Get a file objectTo write output to a file:
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()
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()