Pathlib
File and directory access
The OS
library in python which handles almost all the basic file system operations. Now the Pathlib
, which is a built-in python library. it is intuitive in terms of syntax, easier to use, and has more features out of the box. Paths are not strings.
Show Current Directory
from pathlib import Path
# Current Working Directory
Path.cwd()
# User Home Directory
home_dir = Path.home()
# Relative path to the current folder
p = Path() # PosixPath('.')
# Parent of path
p.parent
The OS
library will return a string, whereas the Pathlib will return an object of PosixPath
.
Component of Path
.name
: the file name without any directory.parent
: the directory containing the file, or the parent directory if path is a directory.stem
: the file name without the suffix.suffix
: the file extension.anchor
: the part of the path before the directories
Check Directory of File Existing
OS Library
The function os.path.exists(str_path)
takes a string type argument, which can be either the name of a directory or a file.
import os
os.path.exists('/use/Username/Desktop/try.python')
Pathlib
When using the Pathlib, we simply pass the path as a string to the "Path" class, which will give us a "PosixPath" object.
from pathlib import Path
Path('some_path/README.md').exists()
Create a Directory
from pathlib import Path
Path('test_dir').mkdir()
# check if file exist
Path('test_dir').mkdir(exist_ok=True)
The function mkdir()
accepts a flag exist_ok
. When it is set to true, the FileExistsError
error is automatically ignored. When its parent directories are not existing. we just need to set the flag parents
to true.
Creating a path by passing folder and filename
p = Path('folder_name', 'filename.json')
Relative path to another path
p1 = Path('folder1', 'filename.txt')
p2 = Path('folder1')
p_relative = p1.relative_to(p2)
p_relative
# PosixPath('filename.txt')
Comparing two paths
p1 = Path('folder1', 'filename.txt')
p2 = p1.resolve()
p1.samefile(p2)
Join Path
from pathlib import Path
Path.home() / 'python' / 'scrupts' / 'test.py'
# OR
Path.home().joinpath('python', 'scripts', 'tests.py')
File or directory
p1.is_dir()
p1.is_file()
Moving files with pathlib
from pathlib import Path
path = Path('names.txt')
path.rename('mynames.txt')
p = Path('folder1', 'file1.json')
# Move file1 into folder2 and rename it as file-1
p.rename(Path('folder2', 'file-1.json'))
Copy file
from pathlib import Path
from shutil import copyfile
source = Path('words.txt')
destination = Path('words_bck.txt')
copyfile(source, destination)
Path touch
from pathlib import Path
Path('myfile.txt').touch()
Show Directory Content
When we want to show the content of a directory.
Path('sample_data').iterdir()
The OS
library doesn't provide the feature to search files using wildcards. Therefore, we have to import another library called Glob to help.
from glob import glob
list(glob(os.path.join('sample_data', '*.csv')))
from pathlib import Path
list(Path('sample_data').glob('*.csv'))
Quick Read/Write to File
path = Path.cwd() / 'README.md'
with open(path, mode='r') as f:
print(f.read())
# OR
with path.open(mode='r') as f:
print(f.read())
f = Path('test_dit/test.txt')
f.read_text()
f.write_text('This is a first line')
Metadata of the File
Converting a relative path to an absolute path
# Absolute path of a file
p.resolve()
# Get filename without extension
f.stem
# Get file extension
f.suffix
# Get statistics, create/update time
f.stat()
# Get the size of the file.
f.stat().st_size
Last updated
Was this helpful?