Page 1 of 1

Creating, Renaming and Deleting Directories using the OS module

#1 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,055
  • Joined: 28-December 10

Posted 16 October 2012 - 12:30 AM

Basic Python 2.7 OS Directory/File Manipulation

Let's get this out of the way first, this topic does not cover File I/O, as there is an existing thread for that one already.

Let's do this!

Manipulating files and directories in Python is very easy. In fact, I used it to create a script to rename multiple files inside a directory based on the content of the files(take that, Java!) and I did it quite easily.

This tutorial will cover the following:

1. Creating directories
2. Renaming directories
3. Deleting directories

The meat of the manipulation of directories and files are in the OS module of Python. We need to import the os module first, easily done with this:
import os

Now that we've imported it, let's rock!

Creating a directory
Let's try creating a directory on C:\! Make sure that the directory doesn't exist, or that the path isn't write protected, or else we'll get an OSError.
Creating a directory is easily done by invoking the os.mkdir method.

Python lists os.mkdir as this:

Quote

os.mkdir(path[, mode])
Create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If the directory already exists, OSError is raised.


See, told you it would raise an error. The optional mode parameter is the numerical representation of the file permissions which you can set if you know how(hint: I don't).
Let's now try to make that directory then! Say you wanted to create a folder named "Cake" for cake related files, we just simply do this:

os.mkdir("C:\Cake")



Check out your C:\ directory and you shall see the brand spanking new "Cake" folder! Unless of course you got an OSError, which in case you should blame yourself for not heeding my warnings. What if we want to add a subdirectory called "Chocolate Cake" for chocolate cake related files? We can simply do this:

os.mkdir("C:\Cake\Chocolate Cake")


That would give us our "Chocolate Cake". Now, what if we want to create another folder under "Chocolate Cake", but this time we want two more folder subdirectories? Say we want a "Legendary Chocolate Cake" and underneath it we want to have have "The Most Legendary Chocolate Cake Ever" folder? We should do this, right?

os.mkdir("C:\Cake\Chocolate Cakes\Legendary Chocolate Cake\The Most Legendary Chocolate Cake")


Not so fast, little grasshopper! Python would throw us an error, saying that the path cannot be found. Whaaaaaaat? What if we want to create something like that, a deep folder structure? The method os.makedirs comes to our rescue!

os.makedirs("C:\Cake\Chocolate Cakes\Legendary Chocolate Cake\The Most Legendary Chocolate Cake")


Whoa, no error thrown! We also see that the directory and all folders that aren't existing before exist now. All thanks to the os.makedirs method!

Python lists os.makedirs as this:

Quote

os.makedirs(path[, mode])
Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Raises an error exception if the leaf directory already exists or cannot be created.


Basically, all the directories needed to create the root are created, meaning that if you specify a full path here and that path doesn't exist, the folders will be created. Cool!

Renaming a directory
Now let's head on over to renaming that directory of ours. What if we wanted to rename "The Most Legendary Chocolate Cake" to "Legendary Chocolate Cake 1"? We simply invoke the os.rename method which works on files too!

os.rename("C:\Cake\Chocolate Cakes\Legendary Chocolate Cake\The Most Legendary Chocolate Cake","C:\Cake\Chocolate Cakes\Legendary Chocolate Cake\Legendary Chocolate Cake 1")


This will rename our directory. Go ahead, check it out.

Python lists os.rename as this:

Quote

os.rename(src, dst)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file.


What Python means when the destination is a directory is when you try to change the drive names. That is at least the case for Windows.
What if we wanted to rename the "Cake" directory to "Delicious Foods"? We could do this, right?

os.rename("C:\Cake","C:\Delicious Foods")


Wrong! Again, this will not work since we have to think about the subdirectories of the "Cake" folder. Well, Python has a solution for that, os.renames!

Python lists os.renames as this:

Quote

os.renames(old, new)
Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs().


We can now do this:

os.renames("C:\Cake","C:\Delicious Foods")


It worked! It's magic! Whoa! Now on to the last part, removing directories!

Removing\Deleting\Erasing\Assassinating a Directory
Say we want to delete the "Legendary Chocolate Cake 1" directory since it sounds cheesy, we just invoke the handy os.rmdir method:

os.rmdir("C:\Delicious Foods\Chocolate Cakes\Legendary Chocolate Cake\Legendary Chocolate Cake 1"


That will remove that cheesy folder from the face of the planet. Well, what if we decide to remove the whole "Delicious Foods" folder because it always makes us hungry? Let's simply do this, right?

os.rmdir("C:\Delicious Foods"


Oh no! It threw an error! Well, according to Python, the os.rmdir method is only useful for empty directories, meaning our "Delicious Foods" directory will be safe for the time being. Well, until we call for help from the shutil module!

Python lists os.rmdir as this:

Quote

os.rmdir(path)
Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used.


See where it said shutil? But that's stuff for another tutorial, where we will hopefully tackle moving directories and deleting them when they have contents too.

Hope you learned something from this simple tutorial! ^^

Resources:
Python 2.73 OS module specification

Is This A Good Question/Topic? 0
  • +

Page 1 of 1