Python pathlib module provides an object-oriented approach to work with files and directories. The pathlib module has classes to work with Unix as well as Windows environments. The best part is that we don’t have to worry about the underlying operating system, the pathlib module takes care of using the appropriate class based on the operating system.
Python pathlib Path Class
Path is the most important class in the pathlib module. This is the entry point of all the functions provided by pathlib module. It takes care of instantiating the concrete path implementation based on the operating system and make the code platform-independent.
Python pathlib Module
Let’s look into some examples of using pathlib module.
1. List Subdirectories and Files inside a Directory
We can use Path iterdir() function to iterate over the files in a directory. Then we can use is_dir() function to differentiate between a file and a directory.
from pathlib import Path
# list subdirectories and files inside a directory
path = Path("/Users/pankaj/temp")
subdirs = []
files = []
for x in path.iterdir(): # iterate over the files in the path
if x.is_dir(): # condition to check if the file is a directory
subdirs.append(x)
else:
files.append(x)
print(subdirs)
print(files)
Output:
[PosixPath('/Users/pankaj/temp/spring-webflow-samples'), PosixPath('/Users/pankaj/temp/image-optim'), PosixPath('/Users/pankaj/temp/jersey2-example')]
[PosixPath('/Users/pankaj/temp/test123.py'), PosixPath('/Users/pankaj/temp/.txt'), PosixPath('/Users/pankaj/temp/xyz.txt'), PosixPath('/Users/pankaj/temp/.DS_Store'), PosixPath('/Users/pankaj/temp/db.json'), PosixPath('/Users/pankaj/temp/Test.java'), PosixPath('/Users/pankaj/temp/routes.json'), PosixPath('/Users/pankaj/temp/itertools.py')]
If you run the same program in Windows, you will get instances of WindowsPath.
2. Listing specific type of files
We can use Path glob() function to iterate over a list of files matching the given pattern. Let’s use this function to print all the python scripts inside a directory.
from pathlib import Path
path = Path("/Users/pankaj/temp")
python_files = path.glob('**/*.py')
for pf in python_files:
print(pf)
Output:
Python Pathlib List Files
3. Resolving Symbolic Links to Canonical Path
We can use resolve() function to convert the symbolic links to their canonical path.
py2_path = Path("/usr/bin/python2.7")
print(py2_path)
print(py2_path.resolve())
Output:
/usr/bin/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
4. Check if a File or Directory Exists
The Path exists() function returns True if the path exists, otherwise it returns False.
path = Path("/Users/pankaj/temp")
print(path.exists()) # True
path = Path("/Users/pankaj/temp/random1234")
print(path.exists()) # False
5. Opening and Reading File Contents
We can use Path open() function to open the file. It returns a file object like the built-in open() function.
file_path = Path("/Users/pankaj/temp/test.py")
if file_path.exists() and file_path.is_file():
with file_path.open() as f:
print(f.readlines())
Output:
['import osn', 'n', 'print("Hello World")n']
6. Getting Information of the File
The Path object stat() function make the stat() system call and return the results. The output is the same as the os module stat() function.
file_path = Path("/Users/pankaj/temp/test.py")
print(file_path.stat())
Output:
os.stat_result(st_mode=33188, st_ino=8623963104, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=32, st_atime=1566476310, st_mtime=1566476242, st_ctime=1566476242)
7. Getting the File or Directory Name
We can use “name” property to get the file name from the path object.
print(Path("/Users/pankaj/temp/test.py").name)
print(Path("/Users/pankaj/temp/").name)
print("Path without argument Name :", Path().name)
Output:
test.py
temp
Path without argument Name :
8. Creating and Deleting a Directory
We can use mkdir() function to create a directory. We can use rmdir() to delete an empty directory. If there are files, then we have to delete them first and then delete the directory.
directory = Path("/Users/pankaj/temp/temp_dir")
print(directory.exists()) # False
directory.mkdir()
print(directory.exists()) # True
directory.rmdir()
print(directory.exists()) # False
9. Change File Mode
file = Path("/Users/pankaj/temp/test.py")
file.chmod(0o777)
The chmod() function behaves same as os.chmod() function to change the file permissions.
10. Getting File Group and Owner Name
file = Path("/Users/pankaj/temp/test.py")
print(file.group()) # staff
print(file.owner()) # pankaj
11. Expand ~ to Canonical Path
path = Path("~/temp")
print(path) # ~/temp
path = path.expanduser()
print(path) # /Users/pankaj/temp
12. CWD and Home Path
print(Path.cwd())
print(Path.home())
Output:
/Users/pankaj/Documents/PycharmProjects/PythonTutorials/hello-world
/Users/pankaj
13. Joining Two Paths
path = Path.home()
path = path.joinpath(Path("temp"))
print(path) # /Users/pankaj/temp
14. Creating an empty file
Just like Unix touch command, Path has touch() function to create an empty file. You should have the permissions to create the file. Otherwise, the file won’t be created and there will be no error thrown.
new_file = Path("/Users/pankaj/temp/xyz.txt")
print(new_file.exists()) # False
new_file.touch()
print(new_file.exists()) # True
Python Pathlib Create New File
Conclusion
Python pathlib module is very useful in working with files and directories in an object-oriented way. The loosely coupled and platform-independent code makes it more attractive to use.
Reference: Official Docs – pathlib module