Posted By

chombee on 07/15/08


Tagged

python


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

carlosabargues
gartenstuhl


Creating and removing files and dirs with Python OS module


 / 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

  1. import os
  2.  
  3. # Make a new file.
  4. # Simply opening a file in write mode will create it, if it doesn't exist. (If
  5. # the file does exist, the act of opening it in write mode will completely
  6. # overwrite its contents.)
  7. try:
  8. f = open("file.txt", "w")
  9. except IOError:
  10. pass
  11.  
  12. # Remove a file.
  13. try:
  14. os.remove(temp)
  15. except os.error:
  16. pass
  17.  
  18. # Make a new directory.
  19. os.mkdir('dirname')
  20.  
  21. # Recursive directory creation: creates dir_c and if necessary dir_b and dir_a.
  22. os.makedirs('dir_a/dir_b/dir_c')
  23.  
  24. # Remove an empty directory.
  25. os.rmdir('dirname')
  26. os.rmdir('dir_a/dir_b/dir_c') # Removes dir_c only.
  27.  
  28. # Recursively remove empty directories.
  29. # removedirs removes all empty directories in the given path.
  30. os.removedirs('dir_a/dir_b/dir_c')
  31.  
  32. # Neither rmdir or removedirs can remove a non-empty directory, for that you need the further file
  33. # operations in the shutil module.
  34. # This removes the directory 'three' and anything beneath it in the filesystem.
  35. import shutil
  36. shutil.rmtree('one/two/three')

Report this snippet  

You need to login to post a comment.