/ Published in: Python
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
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
Expand |
Embed | Plain Text
Copy this code and paste it in your 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')