🗂️ File Management

File management in Python is like being a digital organizer for your computer. You can check if files exist, find out information about them, organize them into folders, and keep your file system tidy. These skills are essential for building applications that work reliably with files and directories.

Think of file management as your program's ability to be a helpful assistant - it can check what files are available, organize them properly, and maintain a clean workspace.

import os

# 🎯 File Management Demo

# Check if files exist
print("🔍 Checking file existence:")
test_files = ["example.txt", "missing.txt", "data.csv"]

for filename in test_files:
    if os.path.exists(filename):
        print(f"   ✅ {filename} exists")
    else:
        print(f"   ❌ {filename} not found")

# Create a sample file for testing
with open("sample.txt", "w") as file:
    file.write("This is a sample file for testing.\n")
    file.write("It helps demonstrate file properties.\n")

print("\n📋 File information:")
filename = "sample.txt"

if os.path.exists(filename):
    # Get basic file properties
    size = os.path.getsize(filename)
    is_file = os.path.isfile(filename)
    is_dir = os.path.isdir(filename)
    
    print(f"   📄 {filename}")
    print(f"   Size: {size} bytes")
    print(f"   Is file: {is_file}")
    print(f"   Is directory: {is_dir}")

# List directory contents
print("\n📁 Current directory contents:")
for item in os.listdir("."):
    if os.path.isfile(item):
        print(f"   📄 {item}")
    elif os.path.isdir(item):
        print(f"   📁 {item}")

# Create a directory
new_folder = "my_files"
if not os.path.exists(new_folder):
    os.mkdir(new_folder)
    print(f"\n✅ Created directory: {new_folder}")

🎯 Understanding File System Operations

File management involves checking properties, organizing files, and maintaining directory structures.

📊 File Properties and Information

Understanding file properties helps you make decisions about how to handle different files.

import os
import time

# 📊 File Properties Demo

def analyze_file_properties():
    # Create test files with different content
    test_files = {
        "small.txt": "Small file content.",
        "medium.txt": "Medium file with more content. " * 10,
        "large.txt": "Large file content. " * 100
    }
    
    print("📄 Creating test files:")
    for filename, content in test_files.items():
        with open(filename, "w") as file:
            file.write(content)
        print(f"   ✅ Created {filename}")
    
    print("\n📊 File Analysis:")
    print("-" * 40)
    
    for filename in test_files.keys():
        if os.path.exists(filename):
            # Get file stats
            stats = os.stat(filename)
            
            print(f"\n📄 {filename}:")
            print(f"   Size: {stats.st_size} bytes")
            
            # Convert size to readable format
            size = stats.st_size
            if size > 1024:
                print(f"   Size: {size/1024:.1f} KB")
            
            # Time information
            mod_time = time.ctime(stats.st_mtime)
            print(f"   Modified: {mod_time}")
            
            # File permissions (simplified)
            readable = os.access(filename, os.R_OK)
            writable = os.access(filename, os.W_OK)
            print(f"   Readable: {readable}")
            print(f"   Writable: {writable}")

analyze_file_properties()

📁 Directory Operations

Working with directories lets you organize files into logical groups and create structured file systems.

import os

# 📁 Directory Management Demo

def directory_operations():
    print("📁 Directory operations demo:")
    
    # 1. Create single directory
    single_dir = "documents"
    if not os.path.exists(single_dir):
        os.mkdir(single_dir)
        print(f"   ✅ Created directory: {single_dir}")
    
    # 2. Create nested directories
    nested_path = "projects/python/file_ops"
    try:
        os.makedirs(nested_path, exist_ok=True)
        print(f"   ✅ Created nested path: {nested_path}")
    except Exception as e:
        print(f"   ❌ Error creating path: {e}")
    
    # 3. List directory contents
    print(f"\n📋 Contents of current directory:")
    try:
        items = os.listdir(".")
        files = [item for item in items if os.path.isfile(item)]
        dirs = [item for item in items if os.path.isdir(item)]
        
        print(f"   📄 Files: {len(files)}")
        for file in files[:5]:  # Show first 5 files
            size = os.path.getsize(file)
            print(f"      {file} ({size} bytes)")
        
        print(f"   📁 Directories: {len(dirs)}")
        for directory in dirs[:5]:  # Show first 5 directories
            print(f"      {directory}/")
            
    except Exception as e:
        print(f"   ❌ Error listing directory: {e}")
    
    # 4. Check directory properties
    print(f"\n🔍 Directory information:")
    for dir_name in [single_dir, "projects"]:
        if os.path.exists(dir_name):
            is_dir = os.path.isdir(dir_name)
            can_write = os.access(dir_name, os.W_OK)
            print(f"   📁 {dir_name}: directory={is_dir}, writable={can_write}")

directory_operations()

🔍 File Organization and Cleanup

Organizing files automatically helps maintain a clean and efficient file system.

import os
import time

# 🗂️ File Organization Demo

def organize_files():
    print("🗂️ File organization demo:")
    
    # Create sample files for organization
    sample_files = [
        "report.pdf", "data.csv", "script.py", 
        "image.jpg", "document.txt", "backup.zip"
    ]
    
    print("📄 Creating sample files:")
    for filename in sample_files:
        with open(filename, "w") as file:
            file.write(f"Sample content for {filename}")
        print(f"   ✅ Created {filename}")
    
    # Define organization categories
    categories = {
        "Documents": [".pdf", ".txt", ".doc"],
        "Data": [".csv", ".json", ".xml"],
        "Scripts": [".py", ".js", ".html"],
        "Images": [".jpg", ".png", ".gif"],
        "Archives": [".zip", ".tar", ".gz"]
    }
    
    print(f"\n📂 Organizing files by type:")
    
    # Create category directories
    for category in categories.keys():
        if not os.path.exists(category):
            os.mkdir(category)
            print(f"   📁 Created {category} folder")
    
    # Organize files
    current_files = [f for f in os.listdir(".") if os.path.isfile(f)]
    
    for filename in current_files:
        # Get file extension
        _, ext = os.path.splitext(filename)
        ext = ext.lower()
        
        # Find matching category
        moved = False
        for category, extensions in categories.items():
            if ext in extensions:
                try:
                    # Move file to category folder
                    old_path = filename
                    new_path = os.path.join(category, filename)
                    os.rename(old_path, new_path)
                    print(f"   📦 Moved {filename} to {category}/")
                    moved = True
                    break
                except Exception as e:
                    print(f"   ❌ Error moving {filename}: {e}")
        
        if not moved and filename in sample_files:
            print(f"   ⚠️ No category for {filename}")

organize_files()

🛠️ File System Maintenance

Regular maintenance keeps your file system organized and prevents issues.

🧹 File Cleanup and Maintenance

import os
import time

# 🧹 File Maintenance Demo

def file_maintenance():
    print("🧹 File maintenance demo:")
    
    # Create some old and new files for demo
    test_files = ["old_log.txt", "recent_data.csv", "temp_file.tmp"]
    
    for i, filename in enumerate(test_files):
        with open(filename, "w") as file:
            file.write(f"Content for {filename}")
        
        # Make some files appear "older"
        if "old" in filename or "temp" in filename:
            # Set modification time to 30 days ago
            old_time = time.time() - (30 * 24 * 60 * 60)
            os.utime(filename, (old_time, old_time))
    
    print("   📄 Created test files with different ages")
    
    # File maintenance analysis
    print(f"\n📊 File analysis:")
    current_time = time.time()
    old_files = []
    large_files = []
    temp_files = []
    
    for filename in os.listdir("."):
        if os.path.isfile(filename):
            stats = os.stat(filename)
            
            # Check file age (older than 7 days)
            days_old = (current_time - stats.st_mtime) / (24 * 60 * 60)
            if days_old > 7:
                old_files.append((filename, int(days_old)))
            
            # Check file size (larger than 1KB)
            if stats.st_size > 1024:
                large_files.append((filename, stats.st_size))
            
            # Check for temporary files
            if filename.endswith(('.tmp', '.temp', '.bak')):
                temp_files.append(filename)
    
    # Report findings
    print(f"   📅 Old files (>7 days): {len(old_files)}")
    for filename, age in old_files[:3]:
        print(f"      {filename} ({age} days old)")
    
    print(f"   📦 Large files (>1KB): {len(large_files)}")
    for filename, size in large_files[:3]:
        print(f"      {filename} ({size} bytes)")
    
    print(f"   🗑️ Temporary files: {len(temp_files)}")
    for filename in temp_files:
        print(f"      {filename}")
    
    # Cleanup suggestions (simulation mode)
    print(f"\n💡 Cleanup suggestions:")
    if old_files:
        print(f"   Consider archiving {len(old_files)} old files")
    if temp_files:
        print(f"   Can safely delete {len(temp_files)} temporary files")
    if large_files:
        print(f"   Review {len(large_files)} large files for compression")

file_maintenance()

📚 File Management Reference

Quick reference for essential file management operations and patterns.

Essential File Management Methods

Understanding core file management methods enables effective file system operations and proper resource handling in Python applications.

MethodPurposeExampleBest Practice
os.path.exists(path)Check if path existsif os.path.exists("file.txt"):Always check before operations
os.path.isfile(path)Check if path is a fileis_file = os.path.isfile(path)Verify file type before access
os.path.isdir(path)Check if path is a directoryis_dir = os.path.isdir(path)Confirm directory before listing
os.path.getsize(path)Get file size in bytessize = os.path.getsize("file.txt")Check size before reading
os.listdir(path)List directory contentsfiles = os.listdir(".")Use for directory exploration
os.mkdir(path)Create single directoryos.mkdir("new_folder")Check existence first
os.makedirs(path)Create directory treeos.makedirs("path/to/folder")Use exist_ok=True for safety
os.rename(old, new)Rename file or directoryos.rename("old.txt", "new.txt")Ensure destination doesn't exist

File management is a crucial skill for Python developers. These techniques help you build robust applications that can organize files, maintain clean systems, and handle file operations reliably.

Test Your Knowledge

Test your understanding of file management concepts:

What's Next?

Congratulations! You've completed the File Operations section. You now understand how to read files, write files, and manage your file system effectively.

Ready to continue your Python journey? Check out our next section on Code Organization to learn how to structure your code into reusable modules.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent