1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Putting It All Together With Syntax

By Al Lukaszewski, About.com

4 of 10

File Input and Output

As with everything in Python, files are objects. To open a file object, you must assign it to a variable as follows:

a = open("sample.txt")

By default, the open command takes a minimum of one and possibly two arguments: the name of the file to open and the control, or permission, you would like the program to exercise over that file. The two basic ways to open a file are for reading ('r') and writing ('w'). If the file is a binary file, instead of text, you can follow the 'r' or the 'w' with a 'b' to tell Python to deal with the file accordingly.

The following example opens a file for reading. It then reads every line of the file, printing it to the screen, and closes the file at the end.

a = open("sample.txt", "r")
line = a.readline()
while line:
     print line
     line = a.readline() # Note that the content of line changes
          # here, resetting the loop

a.close()

Writing to a file is even easier. The following code opens a file, 'output.txt', for writing and writes a sample line to it, complete with a newline at the end.

a = open("output.txt", "w")
a.write("This is a sample line.\n")

4 of 10

Explore Python

More from About.com

  1. Home
  2. Computing & Technology
  3. Python

©2008 About.com, a part of The New York Times Company.

All rights reserved.