Home > Articles > Open Source > Python

  • Print
  • + Share This
Like this article? We recommend

File Input and Output

The following program opens a file and reads its contents line by line:

f = open("foo.txt")    # Returns a file object
line = f.readline()    # Invokes readline() method on file
while line:
    print line,    # trailing ',' omits newline character
    line = f.readline()
f.close()

The open() function returns a new file object. By invoking methods on this object, you can perform various file operations. The readline() method reads a single line of input, including the terminating newline. The empty string is returned at the end of the file. To make the output of a program go to a file, you can give the file to the print statement using >> as shown in the following example:

f = open("out","w")   # Open file for writing
while year <= numyears:
    principal = principal*(1+rate)
    print >>f,"%3d  %0.2f" % (year,principal)
    year += 1
f.close()

In addition, files support a write() method that can be used to write raw data. For example, the print statement in the previous example could have been written this way:

f.write("%3d  %0.2f\n" % (year,principal))
  • + Share This
  • 🔖 Save To Your Account