Working with File Paths

The Python standard library contains a very useful module for working with file paths: os.path. There is also related functionality scattered through various other modules in the standard library.

If you don't want to be dependent on the Python standard library in your IronPython code, you may want to use .NET classes instead. .NET provides tools for working with paths in the System.IO namespace.

Particularly relevant are the following classes:


 * Directory
 * File
 * Path

The Path Class
The Path class has several useful static methods for working with file paths (strings).

These include the following:

Joining Paths
This is an equivalent of os.path.join, it is used to join paths together. For example: from System.IO import Directory, Path filename = 'test.txt' directory = Directory.GetCurrentDirectory

fullPath = Path.Combine(directory, filename)

Extensions
There are several methods for handling file extensions: filenameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath) extension = Path.GetExtension(fullPath)

newPath = Path.ChangeExtension(fullPath, '.new')

if not Path.HasExtension(newPath): print 'How on earth did this happen?'

Splitting Paths
The Path class provides two methods to get the filename and directory part of a path: filename = Path.GetFileName(fullPath) directory = Path.GetDirectoryName(fullPath)

Absolute Paths
There are methods that will tell you whether a path is an absolute path or not, and to turn a path into an absolute path (relative paths will be interpreted relative to the current directory): if not Path.IsPathRooted(fullPath): fullPath = Path.GetFullPath(fullPath)

Temporary Files
Path can either create a temporary file for you (with a .TMP file extension), or return you the path to the 'temporary folder' on the system: tempFolder = Path.GetTempPath

tempFilename = Path.GetTempFileName You are responsible for deleting files created with GetTempFileName!

The File Class
This class provides static methods for the creation, copying, deletion, moving, and opening of files.

We'll cover reading from and writing to files (the .NET way), in another entry, but there are a few other useful methods on this class.

Copying, Deleting and Moving (etc)
This code checks if a file exists, copies it to a new location and then deletes the original: if File.Exists(filename): File.Copy(filename, newFilename) File.Delete(filename) This code does the same thing, but using Move rather than Copy and Delete. It also checks for an IOError: if File.Exists(filename): try: File.Move(filename, newFilename) except IOError, e:       print "Failed to move %s, error was:\n%s" % (newFilename, e) The new filename can be a directory (in which case the filename will be preserved) or a full path.

Replace is similar to Move, except that it creates a (named) backup of the original. File.Replace(filename, newFilename, backupName) It also takes an optional fourth argument (True or False) as to whether it should ignore errors when creating hte backup.

File Attributes
There are a whole bevy of methods on File for getting and setting file attributes; these include creation time, modification time, last accessed time and so on.

Rather than document them here, you can look them up in the File Members Page.

The Directory Class
The Directory class exposes static methods for creating, moving, and iterating over directories and subdirectories.

Current Directory
Setting and getting the current directory: directory = Directory.GetCurrentDirectory

newDirectory = Path.Combine(directory, 'SubDir') Directory.SetCurrentDirectory(newDirectory)

Directory Paths
There are several methods for working with paths and drive names. allDrives = list(Directory.GetLogicalDrives)
 * 1) GetLogicalDrives returns a string collection
 * 2) For use in Python, it is more convenient to
 * 3) turn it into a list.

thisDrive = Directory.GetDirectoryRoot(fullPath) parentDirectory = Directory.GetParent(fullPath)

Checking, Creating and Moving
The following code checks if a directory exists, if not then it creates it, and moves another directory into it. if not Directory.Exists(destParent): Directory.CreateDirectory(destParent)

destDir = Path.Combine(destParent, 'Destination') Directory.Move(sourceDir, destDir) CreateDirectory will create all the directories in the specified path. This might involve creating some of the parent directories of the path if they don't already exist.

Move moves the directory and all its contents to the specified path. If the destDir already exists then an IOError will be raised.

Iterating Over Directory Contents
Directory has three methods for iterating over a directories contents.

They all return string collections, which you can iterate over. For some operations it may be convenient to wrap the call with list( .. ) to return a Python list. Directory.GetFiles(path)
 * 1) Get all the files in the directory

Directory.GetDirectories(path)
 * 1) Get all the subdirectories of a directory

Directory.GetFileSystemEntries(path)
 * 1) Get all entries in a directory

These methods all take an optional second string item, which is a 'search pattern' (using wildcard matching) to filter the results.

For more details, including methods for getting and setting directory attributes, see the Directory Members page.

Find files recursively
The following code finds all "*.py" files on the C:/ drive.

from System.IO import Directory, SearchOption Directory.GetFiles("C:/", "*.py", SearchOption.AllDirectories)

Back to Contents.