Python
  Home arrow Python arrow Page 3 - 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 
IBM Rational Software Development Conference
 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 / 74
    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

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    File Management in Python - Directories
    (Page 3 of 5 )

     

    Directories, like regular files, are easy to work with. Let's start by listing the contents of a directory: 

    import os

    for fileName in os.listdir ( '/' ):

       print fileName 

    As you can see, this is extremely simple, and it can be done in three lines.

     

    Creating a directory is also simple: 

    import os

    os.mkdir ( 'testDirectory' ) 

    It is equally as easy to delete the directory we just created: 

    import os

    os.rmdir ( 'testDirectory ) 

    We can also create multiple directories at a time: 

    import os

    os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' ) 

    Assuming we add nothing to the directories we just created, we can also delete them all at once: 

    import os

    os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' ) 

    Suppose we want to perform a specific action when a specific file type is reached. This can easily be done with the "fnmatch" module. Let's print the contents of all the ".txt" files we encounter and print the filename of any ".exe" files we encounter: 

    import fnmatch

    import os

    for fileName in os.listdir ( '/' ):

       if fnmatch.fnmath ( fileName, '*.txt' ):

          print open ( fileName ).read()

       elif fnmatch.fnmatch ( fileName, '*.exe' ):

          print fileName 

    The asterisk character can represent any amount of characters. If we want to match just one character, we can use the question mark: 

    import fnmatch

    import os

    for fileName in os.listdir ( '/' ):

       if fnmatch.fnmatch ( fileName, '?.txt' ):

          print 'Text file.' 

    It is also possible to create a regular expression using the "fnmatch" module, matching filenames with the "re" module:

     

    import fnmatch

    import os

    import re

    filePattern = fnmatch.translate ( '*.txt' )

    for fileName in os.listdir ( '/' ):

       if re.match ( filePattern, fileName ):

          print 'Text file.'

     

    If we're just looking for one type of filename, it is a lot easier to use the "glob" module. Its patterns are similar to those used in "fnmatch": 

    import glob

    for fileName in glob.glob ( '*.txt' ):

       print 'Text file.' 

    It is also possible to use ranges of characters in the patterns, just as you would in regular expressions. Suppose you want to print the names of text files with one digit before the extension: 

    import glob

    for fileName in glob.glob ( '[0-9].txt' ):

       print fileName 

    The "glob" module makes use of the "fnmatch" module.

     

    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 5 hosted by Hostway