Working with files and directories in Python
This is my OLD blog. I've copied this post over to my NEW blog at:
http://www.saltycrane.com/blog/2008/04/working-with-files-and-directories-in/
You should be redirected in 2 seconds.
I often have a difficult time finding the appropriate functions to work with files and directories in Python. I think one reason is because the Library Reference puts seemingly related functions in two different places: 11 File and Directory Access and 14.1.4 Files and Directories.
Section 11, File and Directory Access contains documentation
for useful functions such as
os.path.exists which checks if a path exists,
glob.glob which is useful for matching filenames using
the Unix-style * and ? wildcards, and
shutil.copy which is similary to the Unix cp
command.
This section includes a total of 11 subsections for modules related
to file and directory access, but it does not contain basic commands
such as os.chdir, os.listdir, or os.rename.
These functions are documented in Section 14.1.4, Files and
Directories, instead.
Here is a summary of some of the functions I find useful. Check the documentation for more complete and detailed information.
11 File and Directory Access-
os.pathmodule:exists- checks if a path or file exists
Example:import os.path print os.path.exists("c:/Windows")Results:True
isfileandisdir- test if the path is a file or directory, respectively.
Example:import os.path print os.path.isfile("c:/Windows") print os.path.isdir("c:/Windows")Results:False True
getmtime- returns the modification time of a path
Example:import os.path import time mtime = os.path.getmtime("c:/Windows") print time.gmtime(mtime)Results:(2008, 4, 2, 15, 58, 39, 2, 93, 0)
-
globmodule:glob: returns a list of paths matching a Unix-style glob pattern.
Example:import glob print glob.glob("c:/windows/*.bmp")Results:['c:/windows\\Blue Lace 16.bmp', 'c:/windows\\Coffee Bean.bmp', 'c:/windows\\default.bmp', 'c:/windows\\FeatherTexture.bmp', 'c:/windows\\Gone Fishing.bmp', 'c:/windows\\Greenstone.bmp', 'c:/windows\\Prairie Wind.bmp', 'c:/windows\\Rhododendron.bmp', 'c:/windows\\River Sumida.bmp', 'c:/windows\\Santa Fe Stucco.bmp', 'c:/windows\\Soap Bubbles.bmp', 'c:/windows\\winnt.bmp', 'c:/windows\\winnt256.bmp', 'c:/windows\\Zapotec.bmp']
-
shutilmodule:copy- similar to Unixcpcopy2- similar to Unixcp -pcopytree- similar to Unixcp -rrmtree- similar to Unixrm -r
chdir- change the current working directorygetcwd- return a string representing the current working directorylistdir- return a list of the names of the entries in the directory.makedir- create a directoryremove- remove a file (this is identical tounlink)rename- rename the file or directorywalk- walks a directory tree (see my os.walk example)
No comments:
Post a Comment