Python OS Module – Useful Methods related to Directory and Files
Python has an OS Module which provides the utility function to working on various parts of the Operating System. The module can be imported in Python using import os
. In this post, we’ll explore some of the functions related to files and directories.
Joining Paths
This method can be useful during the concatenation of the directory and file path.
import os joined_path = os.path.join("first_path/dir", "sub_dir/file.txt") print(joined_path) #first_path/dir\sub_dir/file.txt
Get Current Working Directory
This will get the current working directory of the file.
import os p = os.getcwd() print(p) #C:\Users\pavan\Desktop\python
Creating a Directory
The method mkdir
can be used to create a directory passing the source path and mode. The mode parameter
is the file permission.
os.mkdir('./my_dir_name', mode=775)
Note
Throws FileExistsError
if the directory already exists. And also it cannot be used to create a file.
Check if the Directory is accessible
Before you start any operation of the directory or file. If you want to verify whether that particular file or directory is
accessible with the required permissions than better go for accessible
method.
os.access('C:/Users/pavan/Desktop/python', mode=os.W_OK) #for directory os.access('C:/Users/pavan/Desktop/python/p1.py', mode=os.W_OK) #for file
The available modes are:
- F_OK: Checks if File exists
- W_OK: Checks if File has to write permission
- R_OK: Checks if File has read permission
- X_OK: Checks if File has read, write and execute permissions
Rename Directory
Using method .rename
you can rename a directory or file.
os.rename('source_directory_path', 'destination_directory_path')
Remove Directory
Using method .remove
you can remove a directory or file.
os.remove('path_of_file_to_remove')
Get files within Directory
To fetch a list of all the directories and files within a directory use scandir
method. Which returns an iterator object and through for loop all the directory contents or files will be displayed.
dir = os.scandir('./') for item in dir: print(item)
Check if File is a Directory or File
Apart from access()
the method there is another way to check whether a file or directory is accessible and that is using os.path.isfile()
and os.path.isdir()
.
There is a small difference between access
when compared to isfile
and isdir
is that you can check for accessibility levels in access()
method.
os.path.isdir('source_path') os.path.isfile('source_path')