Python 2.7 – Fundamentals – Files & Directories – Directory Management

Using import

We have examined the basic concepts in core Python. Python has a lot more functionality apart from that. The extra functionality is divided into different modules eg. modules for file handling, network access, databases, numeric processing etc. The reason why they have been divided into separate modules is so that they can be used in your code only if required, thus reducing the size of your code by a large factor.

To include one of these modules, we use the import statement . This imports a particular module into your code and then you can use that module within your code.

For directory management, we use import os . The os module incorporates a lot of functions and methods which let us work with the operating system resources. All methods in this module will use the prefix of os i.e os.method()

Directory Handling

The basic functions that manipulate directories are:

  • Get current directory
  • Changing the current directory
  • List directories and files
  • Creating a new directory
  • Renaming a directory
  • Deleting an empty directory
  • Deleting a non-empty directory

 

Get Current Directory getcwd()

This returns the current working directory as a string

>>> import os
>>> os.getcwd()
'/var/projects/python'
>>>

Changing the Current Directory chdir()

>>> 
>>> import os
>>> os.getcwd()
'/var/projects/python'
>>> os.chdir("/var/downloads")
>>> os.getcwd()
'/var/downloads'
>>>

List Directories and Files listdir()

This lets us list all the files and directories with a directory. Note that it will not recurse into the subdirectories. It needs the path to a directory as an argument.

>> 
>>> import os
>>> os.listdir(os.getcwd())
['jukebox', 'minify', 'FB-photo-albums', 'exceptions.py']
>>> os.chdir("/var/projects")
>>> os.listdir(os.getcwd())
['c', 'python']
>>> os.listdir("/var/projects/c")
['file_lister.c', 'file_lister', 'output.txt']
>>>

Creating a New Directory mkdir()

>>> import os
>>> os.chdir("/var/projects/python")
>>> os.mkdir("test")
>>> os.mkdir("test")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'test'
>>> os.mkdir("test%!# 123")
>>> os.mkdir("test/test2")

As you can see above, the new directory will be made from the current directory unless specified otherwise. If a directory already exists it will throw an exception. You can create directories several levels deep using this function.

 

Renaming A Directory  rename()

The rename function takes two arguments – old name, new name.

>>> import os
>>> os.getcwd()
'/var/projects/python'
>>> os.mkdir("test")
>>> os.rename("test", "testnew")
>>> os.rename("testnew", "testnew")
>>> os.rename("dir_does_not_exist", "testnew")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory
>>>

The rename function throws an exception if the directory does not exist.

Deleting an empty directory rmdir()

>>> import os
>>> os.listdir(".")
['jukebox', 'minify', 'FB-photo-albums', 'exceptions.py', 'testnew']
>>> os.rmdir("testnew")
>>> os.listdir(".")
['jukebox', 'minify', 'FB-photo-albums', 'exceptions.py']
>>>

Deleting a non-empty directory rmtree()

To recursively delete all the contents of a directory, we use another import called shutil as os.rmdir() will throw an exception if we try to delete a non-empty directory.

>>> import os
>>> os.getcwd()
'/var/projects/python'
>>> os.mkdir("test")
>>> os.mkdir("test/test2")
>>> os.rmdir("test")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
OSError: [Errno 66] Directory not empty: 'test'
>>> 
>>> import shutil
>>> shutil.rmtree("test")
>>> os.getcwd()
'/var/projects/python'
>>> os.listdir(".")
['jukebox', 'minify', 'FB-photo-albums', 'exceptions.py']
>>>

In the next post , we will look at File Handling.

1 Trackback / Pingback

  1. Python 2.7 – Fundamentals – Exceptions – Truelogic Blog

Leave a Reply

Your email address will not be published.


*