This is an old copy of the Python FAQ. The information here may be outdated.

How do I delete a file? (And other file questions...)

Use the os.remove function:

os.remove("file.txt")

You sometimes see os.unlink used instead. The two functions are identical; unlink() is simply the name of the Unix system call used by this function.

To remove a directory, use os.rmdir; use os.mkdir to create one. os.makedirs will create any intermediate directories in path that don’t exist. os.removedirs will remove intermediate directories as long as they’re empty; if you want to delete an entire directory tree and its contents, use shutil.rmtree.

To rename a file, use os.rename.

os.rename("file.txt", "new-name.txt")

To truncate a file, open it using for updating, and use the file.truncate method to cut it off:

f = open(filename, "r+")
f.truncate(size)

There’s also os.ftruncate function for files opened with os.open (this operators on low-level file descriptors, not Python file objects).

The shutil module also contains a number of functions to work on files including shutil.copyfile, shutil.copytree, and shutil.rmtree.

To get a list of files, you can use the os.listdir function, or the glob module. The latter supports file patterns, similar to the ones used by the shell, and are often easier to use.

CATEGORY: library

 

A Django site. rendered by a django application. hosted by webfaction.