Using Directory in Python

This post is lesson 41 of 54 in the subject Python Programming Language

To manage a large number of files in a program, it is necessary to organize them into directories for easy management. A directory can contain files or subdirectories. Python also supports the os module to make it easier to work with directories and files.

1. Current directory in Python

1.1. Get the path of the current directory

To get the path of the current directory in Python, we use the getcwd() function in the os module. The getcwd() function returns a string that shows the path of the directory we are currently working in.

import os
print("Path of current directory:", os.getcwd())

Result

Path of current directory: C:\python-examples

In the example above, we are working with the Python code file example.py located in the directory C:\python-examples.

1.2. Change the current directory

Depending on the program’s requirements, we can change the current directory. The os module supports the chdir() function to do this.

import os
print("Path of current directory:", os.getcwd())
# change current directory
os.chdir('C:\Python\Python310')
print("Path of new current directory:", os.getcwd())

Result

Path of current directory: C:\python-examples
Path of new current directory: C:\Python\Python310

2. Get a list of files and subdirectories of a directory

The listdir() function helps get a list of files and subdirectories of a specified directory. If the path is not specified, listdir() will get a list of files and subdirectories of the current directory.

import os
print("List directories and files of Python310 folder:")
print(os.listdir('C:\Python\Python310'))

Result

List directories and files of Python310 folder:
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python310.dll', 'pythonw.exe', 'Scripts', 'share', 'tcl', 'Tools', 'vcruntime140.dll', 'vcruntime140_1.dll']

In the example above, we get the list of directories and files of the directory C:\Python\Python310. The code below will list directories and files of the current directory.

import os
# current directory is C:\python-examples
print("List directories and files of current directory:")
print(os.listdir())

Result

List directories and files of current directory:
['data.txt', 'example.py', 'gochocit.txt', 'main.py', 'Robot', '__pycache__']

3. Create a new directory in Python

The mkdir() function helps create a new directory by providing the full path. If the full path is not provided, the new directory will be created in the current directory.

import os
# create folder hocit in current directory
os.mkdir('hocit')
# create folder hocit in C:\Python\Python310
os.mkdir('C:\Python\Python310\hocit')

4. Rename a directory or file in Python

To rename a directory or file, we use the rename() function. The rename() function has two basic parameters. Parameter 1 is the name (or path) of the old folder or file. Parameter 2 is the name (or path) of the new folder or file.

import os
# list directoris and file before rename()
print("List directoris and file before rename():")
print(os.listdir())
# rename folder
os.rename('hocit', 'datait')
# rename file
os.rename('gochocit.txt', 'data.txt')
# list directoris and file after rename()
print("List directoris and file after rename():")
print(os.listdir())

Result

List directoris and file before rename():
['example.py', 'gochocit.txt', 'hocit']
List directoris and file after rename():
['data.txt', 'datait', 'example.py']

5. Delete a directory or file in Python

A file can be deleted with the remove() function. A directory can be deleted with the rmdir() function.

import os
# list directoris and file before remove
print("List directoris and file before remove:")
print(os.listdir())
# remove folder hocit
os.rmdir('hocit')
# list directoris and file after remove
print("List directoris and file after remove:")
print(os.listdir())

Result

List directoris and file before remove:
['example.py', 'hocit']
List directoris and file after remove:
['example.py']

The rmdir() function can only delete empty folders.

Assuming there is a folder named hocit that contains a file named data.txt. If you attempt to delete using rmdir() at this point, the program will generate an error message.

import os
print(os.listdir())
print(os.listdir('C:\python-examples\hocit'))
os.rmdir('hocit')
print(os.listdir())

Result

['example.py', 'hocit']
['data.txt']
Traceback (most recent call last):
  File "c:\python-examples\example.py", line 4, in <module>
    os.rmdir('hocit')
OSError: [WinError 145] The directory is not empty: 'hocit'

To delete a non-empty folder, we use the rmtree() function in the shutil module.

import os
import shutil
print(os.listdir())
print(os.listdir('C:\python-examples\hocit'))
shutil.rmtree('hocit')
print(os.listdir())

Result

['example.py', 'hocit']
['data.txt']
['example.py']
5/5 - (1 vote)
Previous and next lesson in subject<< Write, Create, and Delete a File in PythonHow to Read an XML file in Python >>

Leave a Reply

Your email address will not be published. Required fields are marked *