Introduction
File path handling helps you find and work with files on your computer in a safe and easy way.
Jump into concepts and practice - no test required
from pathlib import Path # Create a path object p = Path('folder') / 'file.txt' # Check if path exists p.exists() # Get parent folder p.parent # Get file name p.name # Read text from file content = p.read_text()
Path from the pathlib module for easy and safe file path handling./ operator to join folders and files instead of string concatenation.from pathlib import Path # Join folder and file p = Path('my_folder') / 'data.txt' print(p)
p = Path('/home/user/docs') print(p.name) print(p.parent)
p = Path('example.txt') if p.exists(): print('File is here!') else: print('File not found.')
from pathlib import Path # Create a path to a file in a folder folder = Path('my_folder') file_path = folder / 'hello.txt' # Print the full path print(f'Full path: {file_path}') # Print the folder name print(f'Folder: {file_path.parent}') # Print the file name print(f'File name: {file_path.name}') # Check if the file exists if file_path.exists(): print('The file exists!') else: print('The file does not exist.')
pathlib.Path instead of string paths for better safety and clarity./ operator joins paths in a way that works on Windows, Mac, and Linux.exists() to avoid errors when a file or folder might not be there.pathlib.Path and the slash operator to join paths.pathlib module provides an easy and modern way to handle file paths safely.os.path also handles paths, pathlib is recommended for its simplicity and object-oriented approach./ is overloaded to join paths safely./ correctly. Path('folder') + 'file.txt' uses + which is invalid. The .append() and .join() methods do not exist on Path objects.from pathlib import Path
p = Path('folder') / 'subfolder' / 'file.txt'
print(p.parts)parts attribute returns a tuple of each part of the path as separate strings.from pathlib import Path
p = Path('folder') + 'file.txt'
print(p)data.csv exists inside a folder reports before reading it. Which code correctly does this using pathlib?Path('reports') / 'data.csv' which correctly joins folder and file.p.exists() to check if the file exists before reading, which is correct.