📄 File Basics

File basics in Python introduce you to the fundamental concepts of working with files on your computer. Understanding how to open, close, and interact with files safely is the foundation for all file operations in your programs.

Think of files as containers for information that persist even after your program ends - learning to work with them properly ensures your data stays safe and accessible.

# Basic file opening and closing
# Opening a file
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()  # Important: Always close files

# Reading the file we just created
file = open("example.txt", "r")
content = file.read()
print(f"File content: {content}")
file.close()

# Context manager - automatically closes files (RECOMMENDED)
with open("greetings.txt", "w") as file:
    file.write("Hello from Python!")
    file.write("\nThis file will be closed automatically.")

# File is automatically closed here
print("File operations completed safely")

# Reading with context manager
with open("greetings.txt", "r") as file:
    content = file.read()
    print(f"Content: {content}")

# Demonstrate different file modes
filename = "modes_demo.txt"

# Write mode - creates new file or overwrites existing
with open(filename, "w") as file:
    file.write("Original content\n")

# Append mode - adds to end of existing file
with open(filename, "a") as file:
    file.write("Additional content\n")

# Read mode - reads file content
with open(filename, "r") as file:
    content = file.read()
    print(f"Final content:\n{content}")

🎯 Understanding File Operations

File handling requires understanding file modes, proper resource management, and error handling for reliable applications.

File Opening Fundamentals

Understanding how Python opens files and manages file objects is essential for effective file handling.

def demonstrate_file_opening():
    """Show basic file opening concepts"""
    
    # Create a sample file first
    filename = "sample.txt"
    
    # Method 1: Basic open (requires manual closing)
    print("Method 1: Basic file opening")
    file = open(filename, "w")
    file.write("This is a test file.\n")
    file.write("It contains sample data.\n")
    file.close()  # Must remember to close
    print("File created and closed manually")
    
    # Method 2: Context manager (recommended)
    print("\nMethod 2: Context manager (recommended)")
    with open(filename, "r") as file:
        content = file.read()
        print(f"File content:\n{content}")
    # File automatically closed here
    print("File automatically closed by context manager")
    
    # Method 3: Error handling with context manager
    print("\nMethod 3: Safe file opening with error handling")
    try:
        with open("nonexistent.txt", "r") as file:
            content = file.read()
    except FileNotFoundError:
        print("File not found - handled gracefully")
    except PermissionError:
        print("Permission denied - handled gracefully")

demonstrate_file_opening()

File Mode Selection

Choosing the correct file mode ensures your program can perform the intended operations safely.

def file_mode_examples():
    """Demonstrate different file modes and their uses"""
    
    filename = "mode_test.txt"
    
    # Write mode - creates new file or overwrites
    print("1. Write mode ('w') - creates or overwrites")
    with open(filename, "w") as file:
        file.write("Line 1: Original content\n")
        file.write("Line 2: More content\n")
    
    # Read mode - reads existing file
    print("2. Read mode ('r') - reads file content")
    with open(filename, "r") as file:
        content = file.read()
        print(f"Content:\n{content}")
    
    # Append mode - adds to end of file
    print("3. Append mode ('a') - adds to end")
    with open(filename, "a") as file:
        file.write("Line 3: Appended content\n")
    
    # Read updated file
    with open(filename, "r") as file:
        updated_content = file.read()
        print(f"Updated content:\n{updated_content}")
    
    # Read and write mode
    print("4. Read/write mode ('r+') - read and modify")
    with open(filename, "r+") as file:
        # Read current content
        content = file.read()
        # Go back to beginning
        file.seek(0)
        # Write new content
        file.write("Modified: " + content)
        file.truncate()  # Remove any remaining old content
    
    # Show final result
    with open(filename, "r") as file:
        final_content = file.read()
        print(f"Final content:\n{final_content}")

file_mode_examples()

⚡ Text Encoding and Binary Files

Understanding text encoding and binary file handling ensures your programs work with different file types correctly.

def encoding_and_binary_examples():
    """Demonstrate text encoding and binary file handling"""
    
    # Text file with encoding
    print("1. Text files with encoding")
    text_content = "Hello, World! 🌍\nPython supports Unicode! 🐍"
    
    # Save with UTF-8 encoding (recommended)
    with open("unicode_text.txt", "w", encoding="utf-8") as file:
        file.write(text_content)
    
    # Read with matching encoding
    with open("unicode_text.txt", "r", encoding="utf-8") as file:
        content = file.read()
        print(f"Unicode content: {content}")
    
    # Binary file example
    print("\n2. Binary file handling")
    binary_data = b"This is binary data: \x00\x01\x02\x03"
    
    # Write binary data
    with open("binary_file.bin", "wb") as file:
        file.write(binary_data)
    
    # Read binary data
    with open("binary_file.bin", "rb") as file:
        read_data = file.read()
        print(f"Binary data: {read_data}")
        print(f"Data type: {type(read_data)}")
    
    # Working with different encodings
    print("\n3. Different text encodings")
    
    # Create text with special characters
    special_text = "Café, naïve, résumé"
    
    # Save with different encodings
    encodings = ["utf-8", "latin-1", "ascii"]
    
    for encoding in encodings:
        try:
            filename = f"text_{encoding}.txt"
            with open(filename, "w", encoding=encoding) as file:
                file.write(special_text)
            
            # Read back
            with open(filename, "r", encoding=encoding) as file:
                content = file.read()
                print(f"{encoding}: {content}")
        
        except UnicodeEncodeError:
            print(f"{encoding}: Cannot encode special characters")
        except UnicodeDecodeError:
            print(f"{encoding}: Cannot decode file")

encoding_and_binary_examples()

🚀 File Error Handling

Proper error handling ensures your programs can deal with file-related problems gracefully.

import os

def file_error_handling_examples():
    """Demonstrate comprehensive file error handling"""
    
    def safe_file_read(filename):
        """Safely read file with comprehensive error handling"""
        try:
            with open(filename, "r", encoding="utf-8") as file:
                content = file.read()
                print(f"✅ Successfully read {filename}")
                return content
        
        except FileNotFoundError:
            print(f"❌ File not found: {filename}")
            return None
        
        except PermissionError:
            print(f"❌ Permission denied: {filename}")
            return None
        
        except UnicodeDecodeError:
            print(f"❌ Encoding error: {filename}")
            return None
        
        except Exception as e:
            print(f"❌ Unexpected error: {e}")
            return None
    
    def safe_file_write(filename, content):
        """Safely write file with error handling"""
        try:
            with open(filename, "w", encoding="utf-8") as file:
                file.write(content)
                print(f"✅ Successfully wrote {filename}")
                return True
        
        except PermissionError:
            print(f"❌ Permission denied writing: {filename}")
            return False
        
        except OSError as e:
            print(f"❌ System error: {e}")
            return False
        
        except Exception as e:
            print(f"❌ Unexpected error: {e}")
            return False
    
    # Test error handling
    print("Testing file error handling:")
    
    # Test reading existing file
    safe_file_write("test_file.txt", "This is test content")
    safe_file_read("test_file.txt")
    
    # Test reading non-existent file
    safe_file_read("missing_file.txt")
    
    # Test writing to invalid location (may work on some systems)
    safe_file_write("/invalid/path/file.txt", "content")
    
    # File existence checking
    def check_file_safely(filename):
        """Check file properties safely"""
        if os.path.exists(filename):
            try:
                size = os.path.getsize(filename)
                print(f"📄 {filename}: {size} bytes")
                
                # Check if readable/writable
                readable = os.access(filename, os.R_OK)
                writable = os.access(filename, os.W_OK)
                print(f"   Readable: {readable}, Writable: {writable}")
                
            except OSError as e:
                print(f"❌ Error checking {filename}: {e}")
        else:
            print(f"❓ {filename} does not exist")
    
    print("\nFile property checking:")
    check_file_safely("test_file.txt")
    check_file_safely("missing_file.txt")

file_error_handling_examples()

Essential File Operations Methods

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

MethodPurposeExampleBest Practice
open(file, mode)Open file with specified modeopen("data.txt", "r")Always use with context manager
file.read()Read entire file contentcontent = file.read()Good for small files
file.readline()Read single lineline = file.readline()Process files line by line
file.readlines()Read all lines into listlines = file.readlines()Use for small to medium files
file.write(text)Write text to filefile.write("Hello")Returns number of characters written
file.writelines(list)Write list of stringsfile.writelines(lines)Add newlines manually if needed
file.seek(position)Move to position in filefile.seek(0)Reset to beginning
file.tell()Get current positionpos = file.tell()Track file pointer location

Learn more about reading files to explore advanced techniques for processing file content efficiently.

Test Your Knowledge

Test what you've learned about file basics:

What's Next?

Now that you understand file basics, you're ready to explore reading files in detail. Learn how to process file content efficiently, handle different file formats, and work with large files.

Ready to continue? Check out our lesson on Reading Files.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent