File I/O
2002-03-14 03:14:02
Category: python:files
Description: Shows how to read and write to files in python.
Author: mind
Viewed: 12439
Rating: (61 votes)


#!/usr/local/bin/python
#
# File I/O example by mind@metalshell.com
#
# an example on reading and writing to files
#
# 03/12/2002
#
# http://www.metalshell.com
#
 
# import the module sys, this way we can perform system commands such as exit
import sys
 
# Writing to a file:
 
# define file_name as a string that will store input from the keyboard
file_name = raw_input("Enter filename: ")
 
if len(file_name) == 0:
  print "Next time please enter something."
  sys.exit()
 
file_finish = "END!"
file_text = ""
 
# use try: and except: for catching error messages and avoiding them on contact
# when you write your own program you will get a warning saying ??Error: <error message>
# just change IOError to the ??Error you get and you can cleaning exit the program
 
try:
  # open file stream
  file = open(file_name, "w")
except IOError:
  print "There was an error writing to", file_name
  sys.exit()
 
print "Enter '", file_finish,
print "' When finished"
 
while file_text != file_finish:
  file_text = raw_input("Enter text: ")
 
  if file_text == file_finish:
    # close the file
    file.close
    break
 
  # write out the input from the keyboard to the file
  file.write(file_text)
  file.write("\n")
 
file.close()
 
# Reading a file:
 
file_name = raw_input("Enter filename: ")
 
if len(file_name) == 0:
  print "Next time please enter something"
  sys.exit()
 
try:
  file = open(file_name, "r")
except IOError:
  print "There was an error reading file"
  sys.exit()
 
file_text = file.read()
file.close()
 
print file_text
 
print "Example finished!"