Python
  Home arrow Python arrow File Management in Python
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

File Management in Python
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 73
    2005-01-31

    Table of Contents:
  • File Management in Python
  • Getting Information on Existing Files
  • Directories
  • Pickling Data
  • Creating In-memory Files

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    PCmover - $15 Off with Coupon Code CJPH7Q

    File Management in Python
    (Page 1 of 5 )

    File management is a basic function, and an important part of many applications. Python makes file management surprisingly easy, especially when compared to other languages. Peyton McCullough explains the basics.

     

    Introduction

     

    The game you played yesterday uses files to store game saves. The order you placed yesterday was saved in a file. That report you typed up this morning was, obviously, stored in a file as well.

     

    File management is an important part of many applications written in nearly every language. Python is no exception to this. In this article, we will explore the task of manipulating files using several modules. We'll read, write to, append and do other strange things to files. Let's get started.

     

    Reading and Writing

     

    The most basic tasks involved in file manipulation are reading data from files and writing data to files. This is a very simple task to learn. Let's open a file for writing: 

    fileHandle = open ( 'test.txt', 'w' ) 

    The "w" indicates that we will be writing to the file, and the rest is pretty simple to understand. The next step is to write data to the file: 

    fileHandle.write ( 'This is a test.\nReally, it is.' ) 

    This will write the string "This is a test." to the file's first line and "Really, it is." to the file's second line. Finally, we need to clean up after ourselves and close the file: 

    fileHandle.close() 

    As you can see, it's very easy, especially with Python's object orientation. Note that when you use the "w" mode to write to the file again, all its contents will be deleted. To get past this, use the "a" mode to append data to a file, adding data to the bottom: 

    fileHandle = open ( 'test.txt', 'a' )

    fileHandle.write ( '\n\n\nBottom line.' )

    fileHandle.close() 

    Now let's read our file and display the contents: 

    fileHandle = open ( 'test.txt' )

    print fileHandle.read()

    fileHandle.close() 

    This will read the entire file and print the data within it. We can also read a single line in the file: 

    fileHandle = open ( 'test.txt' )

    print fileHandle.readline() # "This is a test."

    fileHandle.close() 

    It is also possible to store the lines of a file into a list: 

    fileHandle = open ( 'test.txt' )

    fileList = fileHandle.readlines()

    for fileLine in fileList:

       print '>>', fileLine

    fileHandle.close() 

    When reading a file, Python's place in the file will be remembered, illustrated in this example: 

    fileHandle = open ( 'test.txt' )

    garbage = fileHandle.readline()

    fileHandle.readline() # "Really, it is."

    fileHandle.close() 

    Only the second line is displayed. We can, however, get past this by telling Python to resume reading from a different position: 

    fileHandle = open ( 'test.txt' )

    garbage = fileHandle.readline()

    fileHandle.seek ( 0 )

    print fileHandle.readline() # "This is a test."

    fileHandle.close() 

    In the above example, we tell Python to continue reading from the first byte in the file. Thus, the first line is printed. We can also request Python's place within the file: 

    fileHandle = open ( 'test.txt' )

    print fileHandle.readline() # "This is a test."

    print fileHandle.tell() # "17"

    print fileHandle.readline() # "Really, it is." 

    It is also possible to read the file a few bytes at a time: 

    fileHandle = open ( 'test.txt' )

    print fileHandle.read ( 1 ) # "T"

    fileHandle.seek ( 4 )

    print FileHandle.read ( 1 ) # "T" 

    When working with Windows and Macintosh, sometimes you are required to read and write files in binary mode, such as images or executional files. To do this, simply append "b" to the file mode: 

    fileHandle = open ( 'testBinary.txt', 'wb' )

    fileHandle.write ( 'There is no spoon.' )

    fileHandle.close()

     

    fileHandle = open ( 'testBinary.txt', 'rb' )

    print fileHandle.read()

    fileHandle.close() 

    More Python Articles
    More By Peyton McCullough


       · Hello!I wrote this article with a "less talk and more code" approach. Does...
       · Good article, I like the code-heavy approach. Another module I find useful is...
       · I like the more-code approach. A nice article.When you're starting out, it's...
       · fileHandle = open ( 'usernames.txt','ab' )fileHandle.write (raw_input("Please...
       · fileHandle.write ( raw_input ( 'Please enter user name to add: ' ) + '\n' )...
       · Hey. I am a python newbie, and reading the "File Management" article helped me...
       · following the nice file i/o tutorial here, i have only one remaining quesiton: how...
       · The article may be good, but it does not explain how to avoid program exit when file...
       · Be consistent with your backslashes, this will solve your problem!
       · thats a more general issue of exception handling, IMHO
       · I get errors when I try to run the first example in - Getting Information on...
     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway