Introduction to Common Python File Handling Modules: os, shutil, and zipfile
This article introduces the commonly used Python file handling modules—os, shutil, and zipfile—explaining their key functions, demonstrating path operations, file copying, moving, and compression/decompression with practical code examples to help readers efficiently manage files and directories.
This article provides a concise tutorial on three essential Python modules for file handling: os, shutil, and zipfile. It explains their main capabilities and includes ready‑to‑run code snippets.
os module offers functions for interacting with the operating system, especially file‑path operations via os.path. Example usage:
# Import the module
import os
# Get current working directory
print("Current working directory:", os.getcwd())
# Get absolute path of a relative path
print("Absolute path:", os.path.abspath("."))
print(os.path.abspath(".."))
print(os.path.abspath("hello.py"))
# Relative path from a start point
print(os.path.relpath("C:\\"))
print(os.path.relpath("C:\\", "hello.py"))
# Check if a path exists
print("File exists:", os.path.exists("hello.py"))shutil module provides high‑level operations for copying, moving, and removing files and directories, as well as handling archive files. Example usage:
import shutil
# Copy a file
shutil.copy("write_test.txt", "write_test_copy.txt")
# Copy a directory
shutil.copytree("source_dir", "dest_dir")
# Move a file or directory
shutil.move("source", "destination")
# Remove a directory tree
shutil.rmtree("dir_to_remove")zipfile module enables creation and extraction of ZIP archives. Example usage:
import zipfile, os, glob
# Create a zip archive
fileZip = zipfile.ZipFile("archive.zip", "w")
for name in glob.glob("my_folder/*"):
fileZip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)
fileZip.close()
# Extract the archive
unpack_zip = zipfile.ZipFile("archive.zip")
unpack_zip.extractall("extracted_folder")
unpack_zip.close()By mastering these modules, developers can efficiently perform common file system tasks, automate file management, and handle compression tasks directly within Python scripts.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
