This article explains Python Directory and Files Management in detail.
Python os Module
Python has certain built-in modules that provide useful methods of directory management, one of them is the Python OS module. To use the python OS module, we need to first import it to our program using syntax:
import os
Python Directory
Directories are used to store, arrange and segregate files on the system. They are majorly used to manage things when there are a large number of files by arranging the code within different directories.
A directory, also known as a folder, is a group of files and subdirectories. The directory which is at the highest level of hierarchy that is the one that does not have a parent is called the root directory.
A string of characters that is used to uniquely define the way to reach the file is called the path of that file. It contains a combination of directory and folder names separated by slashes and colons and gives the location of the file on the computer.
Get Current Directory
To get the current working directory(CWD), we can use the getcwd() method of the OS module. This method returns the path of the current working directory in the form of a string.
The getcwdb() method can also be used, it returns a byte string that represents the current working directory.
Example: Below is the code to show the implementation of both getcwd() and getcwdb() methods of the os module.
Code:
# importing OS module
import os
print("Getting current directory in string format :", os.getcwd())
print("Getting current directory in byte string format :", os.getcwdb())
Output:
Getting current directory in string format : /home/repl/26e08558-2e2b-49a9-8c94-d600119cda50
Getting current directory in byte string format : b'/home/repl/26e08558-2e2b-49a9-8c94-d600119cda50'
Note that in the above example it is returning the path of the directory where you are running this code, so the output may vary.
Changing Directory
Every process running on a computer has a directory associated with it and is known as the current working directory and to change this current working directory os.chdir() method is used.
The new path to which one wishes to change the current directory must be passed as a string to this method as its parameter.
Example: Below is the code showing the implementation of chdir() method.
Code:
import os
# Printing initial directory
print(“Current initial directory is :”, os.getcwd())
# Changing current working directory
os.chdir(‘/home/niharika/Desktop/’)
print(“Current directory is changed to :”, os.getcwd())
Output:
Current initial directory is : /home/niharika/Desktop/documents
The current directory is changed to/home/niharika/Desktop/
List Directories and Files
A directory contains its subdirectories and a number of files in it. To retrieve all of them, the listdir() method of the OS module is used. This method takes zero or one parameter.
In the case where no parameter is passed, it returns the list of sub-directories and files of the current working directory.
If the path is passed as a parameter, then it returns a list of all the subdirectories and files present in that path.
Example: The following code will list all directories and files of the Current Working Directory. Please note that this output varies from where you are running the code so that output may not be the same.
Code:
import os
print(“The files in Current Working Directory are :”,os.listdir(os.getcwd()))
Output:
The files in CWD are : [‘input.fd0138e687.txt’, ‘invocation-standard-error.tmp’, ‘output.fd0138e687.txt’, ‘program.pys3’, ‘RestrictAccess.conf’, ‘restrictaccess.log’, ‘restrictaccess.out’, ‘RestrictAccess32.dll’, ‘runexe2.exe’]
Making a New Directory
To create a new directory, mkdir() method is used. The name of the new directory which you wish to create is passed as a parameter. The path of the dictionary passed as a parameter must contain forward slashes instead of backward slashes. If the full path is not specified then by default it creates a new directory in the current working directory.
Example: Below is the sample code showing making a new directory in the current working directory and on a specified path.
Code:
import os
# Making a new directory in current working directory
os.mkdir(‘new_direc’)
# Making a new directory in D:\
os.mkdir(‘D:/new_direc’)
Renaming a Directory or a File
To rename a directory or a file, the rename() method of the OS module is used.
Two basic arguments are passed to the rename() method, first is the old name of the file or directory and second is the new name.
If the directory or file with the new name already exists then an OSError will be raised in some operating systems.
Example:
import os
os.rename(‘directory1.txt’,’directory1_renamed.txt’)
The os.renames() method takes the old name as the first parameter followed by the destination path of the directory and new name. It works similar to the os.rename() method with extra functionality of providing the destination path of the renamed directory.
Syntax: os.renames(‘old_name’, ‘destination_directory:/new_name’)
Example:
import os
os.renames(‘directory1.txt’, ‘D:/directory1_renamed.txt’)
Removing Directory or File
To remove or delete a directory or a file os.rmdir() method is used. It takes one parameter that is the path of the dictionary to be removed. It deletes only empty directories, otherwise throws an OSError if the directory to be deleted is not empty.
For example, let us consider a directory D:/files. Now we have to first ensure whether it is empty and then proceed for deletion
Code:
import os
dir_list=os.listdir(‘D:/files’)
if len(dir_list)==0:
print(“Error!! Directory not empty!! Cannot be removed”)
else:
os.rmdir(‘D:/files’)
If we want to remove a non-empty directory, rmtree() method present inside the shutil module is used. It will delete the entire directory on the specified path.
Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
Frequently Asked Questions
Q.1. What is a Python directory?
Answer: Directories are used to store, arrange and segregate files on the system. They are majorly used to manage things when there are a large number of files by arranging the code within different directories.
A directory, also known as a folder, is a group of files and subdirectories. The directory which is at the highest level of hierarchy that is the one that does not have a parent is called the root directory.
Q.2. Where is my python directory?
Answer: To find where is your python directory located, you can follow the following code:
>>> import os
>>> import sys
>>> os.path.dirname(sys.executable)
`D:\\Python25`
Q.3. How do I get a list of directories in python?
Answer: A directory contains its subdirectories and a number of files in it. To retrieve all of them, the listdir() method of the OS module is used. This method takes zero or one parameter.
In the case where no parameter is passed, it returns the list of sub-directories and files of the current working directory.
If the path is passed as a parameter, then it returns a list of all the subdirectories and files present in that path.
Example: The following code will list all directories and files of the Current Working Directory. Please note that this output varies from where you are running the code so that output may not be the same.
Code:
import os
print(“The files in Current Working Directory are :”,os.listdir(os.getcwd()))
Output:
The files in CWD are : [‘input.fd0138e687.txt’, ‘invocation-standard-error.tmp’, ‘output.fd0138e687.txt’, ‘program.pys3’, ‘RestrictAccess.conf’, ‘restrictaccess.log’, ‘restrictaccess.out’, ‘RestrictAccess32.dll’, ‘runexe2.exe’]
Q.4. How do I open a directory in Python?
Answer: To open a directory in Python, follow the following syntax:
open(“//home//pi//Desktop//Images”)
Leave a Reply