Python has inbuilt standard libraries and other packages for navigating the file system. Among them include os, shutil and glob. In this tutorial we will be looking at Pathlib a nice library that utilizes an object oriented approach for working with the file system.
The Pathlib package offers classes representing filesystem paths with semantics appropriate for different operating systems.
Let us see how to work with pathlib by comparing it with how we use os.path.
Installation
For Python2 you will need to install it as
pip install pathlib2
Since Python3.4 ,pathlib is now part of the python standard library, hence there is no need to install it.
Let us start
# Load Pathlib
import pathlib
# Check All Methods of Pathlib
dir(pathlib)
# Load Os
import os
# Check All Methods of Pathlib
dir(os.path)
# Get Current Directory Using Os
os.getcwd()
# Get Current Directory Using Path
pathlib.Path.cwd()
# Simple way
from pathlib import Path
Path.cwd()
# Creating A Path From String with os.path
os.path.join('testfolder','example.txt')
# Creating A Path From String with Path
Path('testfolder/example.txt')
# Method 2 Using Forward Slash Operator To Join Path
Path('testfolder') / 'example.txt'
# Using Forward Slash Operator To Join Full Path
Path.home() / 'testfolder' / 'example.txt'
# Method 3 Using JoinPath
Path().joinpath('testfolder', 'example.txt')
#Using JoinPath For Full Path
Path.home().joinpath('testfolder', 'example.txt')
# How to Get the Home Directory with Os.path
os.path.expanduser("~")
# How to Get the Home Directory with Os
os.environ['HOME']
# How to Get the Home Directory with Path
Path.home()
# How to Get the Home Directory with Path
Path('~').expanduser()
# How to Get Absolute Path with OS
os.path.abspath('testfolder/example.txt')
# How to Get Absolute Path with Path
Path('testfolder/example.txt').resolve()
# How to Get Absolute Path with Path
Path('testfolder/example.txt').absolute()
Getting The Components of a Path
os_path = os.path.join('testfolder','example.txt')
p_path = Path('testfolder') / 'example.txt'
dir(os_path)
dir(p_path)
# Get Name of File with Path
p_path.name
# Get Name of File with Os
# os.path.basename('testfolder/example.txt')
os.path.basename(os_path)
# Get Directory Name
p_path.parent
# Get Directory Name
os.path.dirname(os_path)
# Get the File Extension/Suffix with OS
os.path.splitext(os_path)[1]
# Get the File Extension/Suffix with Path
p_path.suffix
# Get the File Stem with OS
os.path.splitext(os_path)[0]
# Get the File Stem with Path
p_path.stem
Making Directory and Files
- os.mkdir()
- os.makedirs()
# Make Directory with Os
os.mkdir('folder001')
# Make directory with Path
Path('folder002').mkdir()
# Create A File If Folder Exist
Path('folder002').mkdir(exist_ok=True)
# Create A File inside folder
Path('folder002/newfile.txt').touch()
Looping Through Subdirectories
import glob
all_dir = glob.glob('testfolder/*.txt')
all_dir
for file in all_dir:
print(file)
# Using Path
p = Path('testfolder')
for file in p.glob('*.txt'):
print(file)
# Checking Subdirectory traversely
# Method 1 with **/
all_sub_dir = Path('testfolder').glob('**/*.txt')
# Show all Folders/Sub folders and their files
list(all_sub_dir)
# Checking Subdirectory traversely
# Method 2 with rglob (recursive glob)
all_sub_dir2 = Path('testfolder').rglob('*.txt')
# Show all Folders/Sub folders and their files
list(all_sub_dir2)
# Using os.walk to get all files
for root,subdir,files in os.walk(os.path.join('testfolder')):
for f in files:
if f.endswith(".txt"):
print(f)
# Using os.walk to get all subdirectory
for root,subdir,files in os.walk(os.path.join('testfolder')):
for s in subdir:
print(s)
Checking Files and Directory and Path
- exists
- is_dir()/isdir()
- is_file()/isfile()
print(os_path)
print(p_path)
# Check if it is a directory
os.path.isdir(os_path)
# Check if it is a directory
os.path.isdir(os.path.join('testfolder'))
# Check if it is a directory
p_path.is_dir()
p_path
# Parent Folder is a Directory
p_path.parent.is_dir()
# Check if it is a file with Os
os.path.isfile('testfolder/example.txt')
# Check if it is a file
p_path.is_file()
Path("example.txt").is_file()
for file in p.glob('*.txt'):
print(file.is_file())
# Moving Files
+ shutil.move()
+ os.replace()
+ Path().replace()
import shutil
shutil.move('testfolder/example001.txt','testfolder/newfolder2/movedexample001.txt')
os.replace('testfolder/example002.txt','testfolder/newfolder2/movedexample002.txt')
# using path
Path('testfolder/example003.txt').replace('testfolder/newfolder2/movedexample003.txt')
File Stats
- os.stat()
- Path.stat()
os.stat('example.txt')
# Using Path
Path('example.txt').stat()
# Owner of File
Path('example.txt').owner()
# Owner/Group of File
Path('example.txt').group()
# Owner of File
os.stat('example.txt').st_uid
# Owner/Group of File
os.stat('example.txt').st_gid
import pwd
pwd.getpwuid(os.stat('example.txt').st_gid)
There are several things we can do with pathlib but these are some of them.
You can check out the entire video tutorial on our youtube channel or below
Thanks for your time
Jesus Saves
By Jesse E.Agbe(JCharis)