"How A Computer Looks at Your Program". Page 4.">
  1. Computing

Beginning Python: Putting It All Together With Syntax


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 

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") 

  1. About.com
  2. Computing
  3. Python
  4. Python Library
  5. File Input and Output

©2014 About.com. All rights reserved.