A directory simply is a structured list of documents and folders. A directory can have sub-directories and files. When we have too many files, Python directory comes in handy in file management with directories and sub-directories.
Python has os
module with multiple methods defined inside for directory and file management.
To create a new directory Python has a function mkdir( )
built into os
module.
Syntax
os.mkdir('name')
Where name
is the directory to be created in the current working location.
Example
>>> import os
>>> os.mkdir('abc') #create a directory abc in current directory
>>> os.mkdir('C:/abc') #create a direcotry abc in C:
Note: Use the forward slash /
while creating directories in another location.
To get the location of the current working directory, Python has a function getcwd( )
built in os
module.
Let’s see how this is done:
>>> import os
>>> os.getcwd() #get the current location
'C:\\Python\\examples'
>>> print (os.getcwd())
'C:\Python\examples'
Python has rename( )
function to rename a directory.
Syntax
os.rename(old_name,new_name)
Here is an example, where we will change the name of the file xyz.txt
to abc.txt
.
>>> import os
>>> os.rename('xyz.txt','abc.txt')
In Python, chdir( )
function defined in module os
is used to change the working directories.
Example
Suppose we want to change our working directory to xyz
folder in D:
. Here is how it is done.
>>> import os
>>> os.chdir('D:/xyz') #this will change our working directory
Python has listdir( )
function in module os
to list all the directories and files in a particular location.
listdir( )
returns a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.'
and '..'
even if they are present in the directory.
Here is an example:
>>> import os
>>> os.listdir()
['files',
'example.txt',
'try.py',
python_logo.png']
The function returned the list of files and directories in our working directory. This output depends upon the directories and files contained within the target directory.
To remove or delete a directory path in Python, rmdir( )
is used which is defined in os module.
rmdir( )
works only when the directory we want to delete is empty, else it raises an OS error.
So here are the ways to remove or delete empty and non-empty directory paths.
Removing empty directories
>>> import os
>>> os.listdir()
['example.txt']
>>> os.rmdir('example.txt')
>>> os.listdir()
[]
Removing non-empty directories
rmdir( )
works only when a directory is empty. If we have to remove or delete the directory path of non-empty directory, we have to use retree( )
funtion defined in shutil
module.
>>> import os
>>> import shutil
>>> os.listdir()
['xyz']
>>> shutil.rmtree('xxyz')
>>> os.listdir()
[]
Removing multiple directories at once
To remove multiple directories at once, Python has function removedirs( )
defined in os
module.
Unlike rmdir( )
, removedirs( )
remove all the parent directories mentioned in the directory path recursively until an exception is raised.
Let’s take a deeper look with an example:
Suppose we have a directory z
inside y
, which is child directory of x
.
Now to remove all three directories at once we can use removedirs( )
in following way.
>>> import os
>>> os.removedirs('x/y/z')
This will delete the directory path of all x
, y
, and z
if no exception is raised.
First it will remove z
, then it will remove z's
parent directory y
and finally y's
parent directory x
.
If y
is non-empty and hence raises and exception while removing, only x
will be deleted.
Here is the tabular list of Python directory methods defined in os module for directory management.
Python directory methods with description |
---|
os.access(path, mode) Use the real uid/gid to test for access to the path. |
os.chdir(path) Used to change the current working directory to the path specified. |
os.chflags(path, flags) Set the flags of path to the numeric flags. |
os.chmod(path, mode) Change the mode of path to the numeric mode. |
os.chown(path, uid, gid) Change the owner and group id of path to the numeric uid and gid . To leave one of the ids unchanged, set it to -1. |
os.chroot(path) Changes the root directory of the current process to the specified path. |
os.fchdir(fd) Changes the current working directory to the directory represented by the file descriptor fd . The descriptor must refer to an opened directory. |
os.getcwd() It returns a string representing the current working directory. |
os.getcwdu() It returns a Unicode object representing the current working directory. |
os.lchflags(path, flags) Set the flags of path to the numeric flags, like chflags( ) , but do not follow symbolic links. |
os.lchmod(path, mode) It changes the mode of path to the numeric mode. |
os.lchown(path, uid, gid) It changes the owner and group id of path to the numeric uid and gid . This function will not follow symbolic links. |
os.listdir(path) Returns a list containing the names of the entries in the directory given by path. |
os.lstat(path) It works like stat( ) , but do not follow symbolic links. |
os.makedirs(path[, mode]) It creates directories recursively. |
os.mkdir( ) Creates a new directory named path. |
os.mkfifo(path[, mode]) Create a FIFO (a named pipe) named path with numeric mode. The default mode is 0666 (octal). |
os.readlink(path) Returns a string representing the path to which the symbolic link points. |
os.removedirs(path) Remove directories recursively starting from child to parent. |
os.rename(src, dst) Rename the directory src to dst . |
os.renames(old, new) It renames the old directories with a new name recursively. |
os.rmdir(path) Removes the directory path specified. |
os.stat(path) Perform a stat system call on the given path. |