# 7_filesystem.py # JAH 090402 # # Useful functions for interacting with the file system # copying a file import shutil shutil.copy('output.txt', 'output2.txt') # renaming a file import os os.rename('output2.txt', 'output3.txt') # getting a list of files in the current directory files = os.listdir('.') print "Files in the current directory: " + str(files) # file paths on Windows: ### absolute path filepath = "C:\\Python25\\blah\\file.txt" print "absolute path (Windows): " + filepath ### relative path filepath = "directory\\subdirectory\\file.txt" print "relative path (Windows): " + filepath # file paths on Unix/Linux/OS X ### absolute path filepath = "/home/john/blah/file.txt" print "absolute path (Linux/OS X): " + filepath ### relative path filepath = "directory/subdirectory/file.txt" print "relative path (Linux/OS X): " + filepath # creating a file path in a platform-independent way ### relative path filepath= "directory" + os.sep + "subdirectory" + os.sep + "file.txt" print "relative path (platform-independent) #1: " + filepath # is equivalent to directoryPath = ["directory", "subdirectory", "file.txt"] filepath = os.sep.join(directoryPath) print "relative path (platform-independent) #2: " + filepath # getting the absolute path of the current directory currentDirectory = os.path.abspath(".") print "currentDirectory #1: " + currentDirectory # is equivalent to currentDirectory = os.path.abspath(os.path.curdir) print "currentDirectory #2: " + currentDirectory # is equivalent to currentDirectory = os.getcwd() print "currentDirectory #3: " + currentDirectory # determine if a file/directory exists if os.path.exists('output.txt'): print "output.txt exists!" else: print "output.txt doesn't exist" # create a directory if it doesn't already exist newDirectory = 'temp' if not os.path.exists(newDirectory): print 'Making a new directory called: ' + newDirectory os.mkdir(newDirectory) # see the following links for lots of other useful file system related functions: # http://docs.python.org/library/os.html # http://docs.python.org/library/os.path.html # http://docs.python.org/library/shutil.html