A common task when parsing files using Python is to either delete the file or at least rename it once the data has been processed. The easiest way to accomplish this is to use the os.remove(newFile) and os.rename(oldFile, newFile) function in the os module. The example in ren_file shows how to rename a file by first detecting whether the new filename already exists and then removing the existing file. Once the existing file has been removed, the rename function can be used to rename the file. import os oldFileName = "/books/python/CH4/code/output.txt" newFileName = "/books/python/CH4/code/output.old" #Old Listing for file in os.listdir("/books/python/CH4/code/"): if file.startswith("output"): print file #Remove file if the new name already exists if os.access(newFileName, os.X_OK): print "Removing " + newFileName os.remove(newFileName) #Rename the file os.rename(oldFileName, newFileName) #New Listing for file in os.listdir("/books/python/CH4/code/"): if file.startswith("output"): print file ren_file.py output.old output.txt Removing /books/python/CH4/code/output.old output.old Output from ren_file.py code |