Search This Blog

Working with Files and Folders in Python Automation

 

Working with Files and Folders in Python Automation

Automating file and folder operations is one of the most common use cases in Python automation. This section covers how to read, write, rename, move, delete files, and work with directories efficiently.


Working with Files in Python

Python provides built-in functions to handle files using the open() function.

Opening and Reading a File

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • "r" mode opens the file for reading.
  • The with statement ensures the file is closed automatically.

Writing to a File

with open("example.txt", "w") as file:
    file.write("This is a new line in the file.")
  • "w" mode overwrites the file. Use "a" to append new content.

Appending to a File

with open("example.txt", "a") as file:
    file.write("\nThis line is added at the end.")

Reading a File Line by Line

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # Removes trailing newline characters

Working with Directories

Python’s os and pathlib modules help manage directories.

Creating a Directory

import os

os.makedirs("new_folder", exist_ok=True)  # Creates folder if it doesn’t exist

Listing Files in a Directory

import os

files = os.listdir(".")  # Lists all files in the current directory
print(files)

Checking If a File or Directory Exists

import os

if os.path.exists("example.txt"):
    print("File exists.")
else:
    print("File not found.")

Renaming a File

import os

os.rename("example.txt", "renamed_file.txt")

Moving a File to Another Folder

import shutil

shutil.move("renamed_file.txt", "new_folder/renamed_file.txt")

Copying a File

import shutil

shutil.copy("new_folder/renamed_file.txt", "backup_copy.txt")

Deleting a File

import os

if os.path.exists("backup_copy.txt"):
    os.remove("backup_copy.txt")
    print("File deleted.")

Deleting an Empty Folder

import os

os.rmdir("new_folder")

Deleting a Folder with Files Inside

import shutil

shutil.rmtree("new_folder")

Working with File Paths Using Pathlib

pathlib provides an object-oriented approach to file handling.

Getting the Current Working Directory

from pathlib import Path

cwd = Path.cwd()
print(f"Current directory: {cwd}")

Joining Paths Efficiently

from pathlib import Path

folder = Path("documents")
file_path = folder / "report.pdf"
print(file_path)

Checking File Properties

file = Path("example.txt")

if file.exists():
    print(f"File size: {file.stat().st_size} bytes")
    print(f"Last modified: {file.stat().st_mtime}")

Working with ZIP Files

Python allows compressing and extracting ZIP files using shutil and zipfile modules.

Creating a ZIP Archive

import shutil

shutil.make_archive("backup", "zip", "documents")

Extracting a ZIP File

import shutil

shutil.unpack_archive("backup.zip", "extracted_files")

Adding Files to a ZIP Archive

import zipfile

with zipfile.ZipFile("new_archive.zip", "w") as zipf:
    zipf.write("example.txt")

Automating File Operations: Example Script

This script organizes files in a folder based on their extensions.

import os
import shutil

source_folder = "downloads"
destination_folders = {
    "Images": [".jpg", ".png", ".jpeg"],
    "Documents": [".pdf", ".docx", ".txt"],
    "Spreadsheets": [".xls", ".xlsx", ".csv"],
}

for filename in os.listdir(source_folder):
    file_path = os.path.join(source_folder, filename)
    
    if os.path.isfile(file_path):
        for folder, extensions in destination_folders.items():
            if filename.lower().endswith(tuple(extensions)):
                folder_path = os.path.join(source_folder, folder)
                os.makedirs(folder_path, exist_ok=True)
                shutil.move(file_path, os.path.join(folder_path, filename))
                print(f"Moved {filename} to {folder_path}")

Run this script to automatically organize files into categorized folders.


Conclusion

This section covered essential file and folder automation tasks, including reading/writing files, renaming, moving, deleting, working with ZIP archives, and organizing files automatically. These techniques are foundational for advanced automation workflows.

Would you like additional examples or modifications?

Popular Posts