Python Tutorial - File Directory Operation

  1. Create a Directory in Python
  2. Get Current Directory in Python
  3. List Directories in Python
  4. Change Working Directory
  5. Rename and Remove a Directory

In Python, if you perform operations on directories, you need import the os module. The functions of os module can be used to do file and directory operations.

Create a Directory in Python

A new directory can be created by using mkdir() method. You have to specify the path in which you want to create the directory. If the path is not specified, the directory will be created in current directory.

>>> import os
>>> os.mkdir("PythonTutorials")

A new directory named PythonTutorials will be created in the current working directory.

Get Current Directory in Python

getcwd() method is used to get the current working directory,

>>> import os
>>> print(os.getcwd())

List Directories in Python

To list the files and subdirectories, listdir() method is used. It lists the files and subdirectories of the Python script file if there is no argument given. Otherwise, it lists the content of the given path.

>>> import os
>>> print(os.listdir())
['DLLs', 'Doc', '', '', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python36.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']
>>> print(os.listdir(r"C:\Program Files"))
['7-Zip', 'Common Files', 'Microsoft Office', 'Windows Sidebar']

Change Working Directory

To change the current working directory, chdir() method is used.

>>> import os
>>> os.chdir("C:/Users/HP/Desktop/Code")
>>> print(os.getcwd())

Rename and Remove a Directory

Rename a Directory

A file or directory can be renamed by using rename() function.

>>> import os
>>> os.rename("PythonTutorials", "Python")

The new name of the directory is Python now.

Remove a Directory

A directory can be removed by using rmdir() method.

>>> import os
>>> os.rmdir('Python')

It removes the directory Python from the system.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.