Revision: 7254
Updated Code
at July 15, 2008 20:56 by chombee
Updated Code
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')
Revision: 7253
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at July 15, 2008 20:44 by chombee
Initial Code
# 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')
Initial URL
Initial Description
Effbot's page on the os module: http://effbot.org/librarybook/os.htm The os module has lots of methods for dealing with files and directories: http://docs.python.org/lib/os-file-dir.html The shutil module: http://docs.python.org/lib/module-shutil.html
Initial Title
Creating and removing files and dirs with Python OS module
Initial Tags
python
Initial Language
Python