Advanced File Handling Techniques
File Paths and Directories
In addition to basic file operations, Python also provides functions and modules for working with file paths and directories. The os
and os.path
modules are commonly used for these tasks.
import os
## Get the current working directory
current_dir = os.getcwd()
print(current_dir)
## Join paths
file_path = os.path.join(current_dir, "example", "file.txt")
print(file_path)
## Check if a file or directory exists
if os.path.exists(file_path):
print("File exists!")
You can retrieve various metadata and attributes about a file, such as its size, creation/modification time, and permissions. The os.stat()
function can be used for this purpose.
import os
from datetime import datetime
file_path = "/path/to/file.txt"
## Get file metadata
file_stats = os.stat(file_path)
print("File size:", file_stats.st_size, "bytes")
print("Created:", datetime.fromtimestamp(file_stats.st_ctime))
print("Modified:", datetime.fromtimestamp(file_stats.st_mtime))
File Handling Utilities
Python's standard library provides several utility functions and modules for advanced file handling tasks, such as:
shutil
: Provides high-level file operations like copying, moving, and deleting files and directories.
tempfile
: Allows you to create temporary files and directories for various use cases.
fileinput
: Enables processing of files in a line-by-line fashion, useful for text processing.
import shutil
## Copy a file
shutil.copy("source.txt", "destination.txt")
## Move a file
shutil.move("old_file.txt", "new_location/new_file.txt")
By exploring these advanced file handling techniques, you can expand your ability to manage files and directories more effectively in your Python projects.