File Management in Python
Learning objectives
By the end of this pill you will be able to:
- check whether a file exists;
- retrieve a file’s name, extension and size;
- rename, copy and delete files;
- use the
os,shutilandpathlibmodules to work with files in Python.
Working with files in Python
In Python we can interact with files in many ways: not only reading and writing them, but also checking whether they exist, inspecting their name, extension and size. These operations are mainly done with the os, shutil and pathlib modules.
Checking whether a file exists
With os:
import os
if os.path.exists("data.txt"):
print("The file exists")
else:
print("The file does not exist")
With pathlib:
from pathlib import Path
file = Path("data.txt")
if file.exists():
print("The file exists")
Separating name and extension
With os:
import os
name, ext = os.path.splitext("report.docx")
print("Name:", name) # report
print("Extension:", ext) # .docx
With pathlib:
file = Path("report.docx")
print(file.stem) # report
print(file.suffix) # .docx
Getting the file size
With os:
import os
size = os.path.getsize("report.docx")
print("Size:", size, "bytes")
With pathlib:
file = Path("report.docx")
print("Size:", file.stat().st_size, "bytes")
Renaming, copying and deleting files
For managing files we can use functions from os and shutil.
Renaming a file:
import os
os.rename("old.txt", "new.txt")
Copying a file:
import shutil
shutil.copy("data.txt", "backup_data.txt")
Deleting a file:
import os
os.remove("old.txt")
With pathlib the same operations become very readable:
file = Path("data.txt")
# rename
file.rename("new_name.txt")
# copy
import shutil
shutil.copy(file, "copy.txt")
# delete
file.unlink()
Summary
os.pathandpathliballow you to work with files.- You can check existence and retrieve extension, name and size.
- With
osandshutilyou can rename, copy and delete files. pathliboffers a more modern and readable approach.
EC