Today, we’ll explore how to read and write files using Python’s pathlib module. It provides methods to perform standard file operations without the need for importing other Python modules like os or shutil.
Writing files with Python pathlib
To begin, let’s assume we have a list of employee names and IDs that we want to write to a file. We use Path from pathlib and its write_text method:
from pathlib import Path
employee_data = "Carlos Rivera, 1001\nLuisa PĂ©rez, 1002\nAna Morales, 1003"
file_path = Path("employees.txt")
file_path.write_text(employee_data)
This code creates a file named employees.txt and writes the string employee ID and names to it.
Append to a text file
To append data, we open our previous created file in append mode (‘a’) and use the write function.
The snippet below adds a new employee, Elena Garcia, to the end of our file contents.
with file_path.open('a') as file:
file.write("\nElena Garcia, 1004")
Reading a file with pathlib
Reading the file is just as straightforward as writing it. We will use the pathlib read_text method.
This code reads the our file contents and prints it:
read_data = file_path.read_text()
print(read_data)
Iterate through text file with pathlib
This loop reads each line in employees.txt and prints it, removing any extra whitespaces from the contents:
with file_path.open() as f:
for line in f:
print(line.strip())
FAQ
Can I check if a file exists using Python and pathlib?
Yes. Make sure to use the exists method of a Path object. It returns True if the file exists, False otherwise.
Example:
if file_path.exists():
with file_path.open('a') as file:
file.write("\nDavid Cortez, 1004")
How to read specific lines from a file with pathlib?
Open the file using a with statement and the open method. Then, iterate through the file with a for loop. Use conditional statements to select specific lines. For example:
with file_path.open('a') as f:
for line in f: if 'condition': print(line).
How can I delete a file from a directory of sub-directory using pathlib?
Use the unlink method on the Path object.
First, make sure the file exists before trying to delete it from your operating system.
if fp.exists():
fp.unlink().