Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



Python Standard Library    (ISBN: 0596000960)


 

 List Price: $29.95
 Our Price: $20.97
 Used Price: $7.70

 Release Date: May, 2001
 Manufacturer: O'Reilly & Associates (Paperback)
 Sales Rank: 102,590

 Author: Fredrik Lundh









More Info

 File I/O 2002-03-14 03:14:02
  python 
Category: source:python:files
Description: Shows how to read and write to files in python.
Platform: unix
Author: mind
Viewed: 11784
Rating: 3.9/5 (60 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
rwfile.py
#!/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!"
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?