Python Intermediate

Python File Handling: Reading and Writing Files

CodingerWeb
CodingerWeb
19 views 45 min read

Working with Files in Python

File handling allows you to read from and write to files on your computer. This is essential for data persistence and processing.

Opening and Closing Files


# Basic file opening
file = open("example.txt", "r")  # Open for reading
content = file.read()
file.close()  # Always close files!

# Better approach: using with statement (automatically closes file)
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed here

# File modes
# "r" - Read (default)
# "w" - Write (overwrites existing file)
# "a" - Append (adds to end of file)
# "x" - Create (fails if file exists)
# "r+" - Read and write
# "b" - Binary mode (e.g., "rb", "wb")

Reading Files


# Create a sample file first
with open("sample.txt", "w") as file:
    file.write("Line 1: Hello, World!
")
    file.write("Line 2: Python is awesome!
")
    file.write("Line 3: File handling is useful!
")

# Method 1: Read entire file
with open("sample.txt", "r") as file:
    content = file.read()
    print("Entire file:")
    print(content)

# Method 2: Read line by line
with open("sample.txt", "r") as file:
    print("
Reading line by line:")
    for line_number, line in enumerate(file, 1):
        print(f"Line {line_number}: {line.strip()}")

# Method 3: Read all lines into a list
with open("sample.txt", "r") as file:
    lines = file.readlines()
    print(f"
Total lines: {len(lines)}")
    for line in lines:
        print(line.strip())

# Method 4: Read one line at a time
with open("sample.txt", "r") as file:
    first_line = file.readline()
    second_line = file.readline()
    print(f"First line: {first_line.strip()}")
    print(f"Second line: {second_line.strip()}")

Writing Files


# Writing to a file (overwrites existing content)
with open("output.txt", "w") as file:
    file.write("This is the first line.
")
    file.write("This is the second line.
")

# Appending to a file
with open("output.txt", "a") as file:
    file.write("This line is appended.
")
    file.write("This is another appended line.
")

# Writing multiple lines
lines_to_write = [
    "Line 1
",
    "Line 2
",
    "Line 3
"
]

with open("multiple_lines.txt", "w") as file:
    file.writelines(lines_to_write)

# Writing formatted data
data = [
    {"name": "Alice", "age": 30, "city": "New York"},
    {"name": "Bob", "age": 25, "city": "Los Angeles"},
    {"name": "Charlie", "age": 35, "city": "Chicago"}
]

with open("people.txt", "w") as file:
    file.write("Name	Age	City
")
    file.write("-" * 20 + "
")
    for person in data:
        file.write(f"{person['name']}	{person['age']}	{person['city']}
")

File Operations and Error Handling


import os

# Check if file exists
filename = "test.txt"

if os.path.exists(filename):
    print(f"{filename} exists")
else:
    print(f"{filename} does not exist")

# Error handling with file operations
def safe_read_file(filename):
    """Safely read a file with error handling"""
    try:
        with open(filename, "r") as file:
            return file.read()
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        return None
    except PermissionError:
        print(f"Error: Permission denied to read '{filename}'")
        return None
    except Exception as e:
        print(f"Error reading file: {e}")
        return None

# Test the function
content = safe_read_file("nonexistent.txt")
if content:
    print(content)

# File information
filename = "sample.txt"
if os.path.exists(filename):
    file_size = os.path.getsize(filename)
    print(f"File size: {file_size} bytes")
    
    # Get file modification time
    import time
    mod_time = os.path.getmtime(filename)
    readable_time = time.ctime(mod_time)
    print(f"Last modified: {readable_time}")

Working with CSV Files


import csv

# Writing CSV files
students = [
    ["Name", "Age", "Grade", "Subject"],
    ["Alice", 20, "A", "Math"],
    ["Bob", 21, "B", "Physics"],
    ["Charlie", 19, "A", "Chemistry"],
    ["Diana", 22, "B", "Biology"]
]

# Write CSV file
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(students)

# Read CSV file
print("Reading CSV file:")
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# Working with CSV as dictionaries
with open("students_dict.csv", "w", newline="") as file:
    fieldnames = ["name", "age", "grade", "subject"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    
    writer.writeheader()
    writer.writerow({"name": "Alice", "age": 20, "grade": "A", "subject": "Math"})
    writer.writerow({"name": "Bob", "age": 21, "grade": "B", "subject": "Physics"})

# Read CSV as dictionaries
print("
Reading CSV as dictionaries:")
with open("students_dict.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(f"Name: {row['name']}, Age: {row['age']}, Grade: {row['grade']}")

Working with JSON Files


import json

# Sample data
data = {
    "students": [
        {"name": "Alice", "age": 20, "grades": [85, 92, 78]},
        {"name": "Bob", "age": 21, "grades": [79, 85, 88]},
        {"name": "Charlie", "age": 19, "grades": [95, 89, 92]}
    ],
    "course": "Python Programming",
    "semester": "Fall 2024"
}

# Write JSON file
with open("class_data.json", "w") as file:
    json.dump(data, file, indent=4)

# Read JSON file
with open("class_data.json", "r") as file:
    loaded_data = json.load(file)
    
print("Course:", loaded_data["course"])
print("Students:")
for student in loaded_data["students"]:
    avg_grade = sum(student["grades"]) / len(student["grades"])
    print(f"  {student['name']}: Average grade {avg_grade:.1f}")

# Working with JSON strings
json_string = json.dumps(data, indent=2)
print("
JSON string:")
print(json_string)

# Parse JSON string
parsed_data = json.loads(json_string)
print(f"
Parsed course: {parsed_data['course']}")

Practice Exercise

Create a personal diary application:


import json
import os
from datetime import datetime

class PersonalDiary:
    def __init__(self, filename="diary.json"):
        self.filename = filename
        self.entries = self.load_entries()
    
    def load_entries(self):
        """Load diary entries from file"""
        if os.path.exists(self.filename):
            try:
                with open(self.filename, "r") as file:
                    return json.load(file)
            except (json.JSONDecodeError, FileNotFoundError):
                return {}
        return {}
    
    def save_entries(self):
        """Save diary entries to file"""
        try:
            with open(self.filename, "w") as file:
                json.dump(self.entries, file, indent=4)
            return True
        except Exception as e:
            print(f"Error saving diary: {e}")
            return False
    
    def add_entry(self):
        """Add a new diary entry"""
        print("
--- New Diary Entry ---")
        title = input("Entry title: ").strip()
        if not title:
            print("Title cannot be empty!")
            return
        
        print("Enter your diary entry (press Enter twice to finish):")
        content_lines = []
        while True:
            line = input()
            if line == "" and content_lines and content_lines[-1] == "":
                break
            content_lines.append(line)
        
        content = "
".join(content_lines).strip()
        if not content:
            print("Entry cannot be empty!")
            return
        
        # Create entry with timestamp
        timestamp = datetime.now().isoformat()
        date_key = datetime.now().strftime("%Y-%m-%d")
        
        if date_key not in self.entries:
            self.entries[date_key] = []
        
        entry = {
            "title": title,
            "content": content,
            "timestamp": timestamp
        }
        
        self.entries[date_key].append(entry)
        
        if self.save_entries():
            print(f"Entry '{title}' saved successfully!")
        else:
            print("Failed to save entry!")
    
    def view_entries(self):
        """View all diary entries"""
        if not self.entries:
            print("No diary entries found!")
            return
        
        print("
--- Your Diary Entries ---")
        for date, day_entries in sorted(self.entries.items(), reverse=True):
            print(f"
📅 {date}")
            print("-" * 40)
            for i, entry in enumerate(day_entries, 1):
                timestamp = datetime.fromisoformat(entry["timestamp"])
                time_str = timestamp.strftime("%H:%M")
                print(f"{i}. {entry['title']} ({time_str})")
                print(f"   {entry['content'][:100]}...")
                print()
    
    def search_entries(self):
        """Search diary entries"""
        query = input("Enter search term: ").strip().lower()
        if not query:
            print("Search term cannot be empty!")
            return
        
        found_entries = []
        for date, day_entries in self.entries.items():
            for entry in day_entries:
                if (query in entry["title"].lower() or 
                    query in entry["content"].lower()):
                    found_entries.append((date, entry))
        
        if found_entries:
            print(f"
--- Search Results for '{query}' ---")
            for date, entry in found_entries:
                timestamp = datetime.fromisoformat(entry["timestamp"])
                time_str = timestamp.strftime("%H:%M")
                print(f"📅 {date} at {time_str}")
                print(f"Title: {entry['title']}")
                print(f"Content: {entry['content'][:200]}...")
                print("-" * 40)
        else:
            print(f"No entries found containing '{query}'")
    
    def export_entries(self):
        """Export entries to text file"""
        if not self.entries:
            print("No entries to export!")
            return
        
        filename = f"diary_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        
        try:
            with open(filename, "w") as file:
                file.write("PERSONAL DIARY EXPORT
")
                file.write("=" * 50 + "

")
                
                for date, day_entries in sorted(self.entries.items()):
                    file.write(f"DATE: {date}
")
                    file.write("-" * 30 + "
")
                    
                    for entry in day_entries:
                        timestamp = datetime.fromisoformat(entry["timestamp"])
                        time_str = timestamp.strftime("%H:%M")
                        
                        file.write(f"Time: {time_str}
")
                        file.write(f"Title: {entry['title']}
")
                        file.write(f"Content:
{entry['content']}
")
                        file.write("
" + "="*50 + "

")
            
            print(f"Diary exported to {filename}")
        except Exception as e:
            print(f"Error exporting diary: {e}")
    
    def run(self):
        """Main diary application loop"""
        print("📖 Welcome to Your Personal Diary!")
        
        while True:
            print("
--- Personal Diary ---")
            print("1. Add new entry")
            print("2. View all entries")
            print("3. Search entries")
            print("4. Export diary")
            print("5. Quit")
            
            choice = input("Choose an option (1-5): ").strip()
            
            if choice == "1":
                self.add_entry()
            elif choice == "2":
                self.view_entries()
            elif choice == "3":
                self.search_entries()
            elif choice == "4":
                self.export_entries()
            elif choice == "5":
                print("Goodbye! Keep writing! 📝")
                break
            else:
                print("Invalid choice! Please try again.")

# Run the diary application
if __name__ == "__main__":
    diary = PersonalDiary()
    diary.run()