Working with Directories in Python
The OS module in python provides functions for interacting with the operating system. This module contains an interface to many operating system-specific functions to manipulate processes, files, file descriptors, directories and other “low level” features of the OS.Current Working Directory
The getcwd() returns the path to the current working directory. This is the directory which the OS use to transform a relative file name into an absolute file name. example
import os
cur_dir = os.getcwd()
print(cur_dir)
List Directory Contents
The listdir() function returns the content of a directory. example
import os
contents = os.listdir()
print(contents)
Create a new Directory/Folder
The mkdir() method creates a new directory. It returns an error if the parent directory does not exist. example
import os
os.mkdir("Temp")
The above example create a new directory "Temp" in the current path.
Creating Subdirectories
import os
os.makedirs("Temp/temp1/temp2/")
Deleting an empty Directory/Folder
The rmdir() method will delete an empty directory or folder. example
import os
os.rmdir("Temp")
Renaming a directory/folder
The os.rename() method can rename a folder from an old name to a new one. example
import os
os.rename("Temp","Temp11")
Related Topics
- How to open and close a file in Python
- How to write files in python
- How to read a file properly in Python
- How to read a file line by line in Python
- How to use Split in Python
- How to check that a file or directory exists with Python
- File Access Mode in Python
- Difference between read, readline and readlines | python
- Python file positions | seek() and tell()
- How to Copy a File using Python