Files

The open() function

     f = open("foo","w")       # Open a file for writing
     g = open("bar","r")       # Open a file for reading

Reading and writing data

     f.write("Hello World")
     data = g.read()           # Read all data
     line = g.readline()       # Read a single line
     lines = g.readlines()     # Read data as a list of lines 

Formatted I/O

  • Use the % operator for strings (works like C printf)
     for i in range(0,10):
         f.write("2 times %d = %d\n" % (i, 2*i))
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 21
July 17, 2000, beazley@cs.uchicago.edu
>>>