Skip to content

Instantly share code, notes, and snippets.

@seanh
Created November 12, 2009 11:11
Show Gist options
  • Save seanh/232821 to your computer and use it in GitHub Desktop.
Save seanh/232821 to your computer and use it in GitHub Desktop.
Creating and removing files and directories with Python os module
"""This is done with the os module, which has lots of methods for handling files and dirs.
<http://docs.python.org/lib/os-file-dir.html>
Effbot's page on the os module: <http://effbot.org/librarybook/os.htm>
The shutil module is useful here also: <http://docs.python.org/lib/module-shutil.html>
"""
import os
# Make a new file.
# Simply opening a file in write mode will create it, if it doesn't exist. (If
# the file does exist, the act of opening it in write mode will completely
# overwrite its contents.)
try:
f = open("file.txt", "w")
except IOError:
pass
# Remove a file.
try:
os.remove(temp)
except os.error:
pass
# Make a new directory.
os.mkdir('dirname')
# Recursive directory creation: creates dir_c and if necessary dir_b and dir_a.
os.makedirs('dir_a/dir_b/dir_c')
# Remove an empty directory.
os.rmdir('dirname')
os.rmdir('dir_a/dir_b/dir_c') # Removes dir_c only.
# Recursively remove empty directories.
# removedirs removes all empty directories in the given path.
os.removedirs('dir_a/dir_b/dir_c')
# Neither rmdir or removedirs can remove a non-empty directory, for that you need the further file
# operations in the shutil module.
# This removes the directory 'three' and anything beneath it in the filesystem.
import shutil
shutil.rmtree('one/two/three')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment