šŸ

File Handling: Reading and Writing Files

Beginner
90 XP
40 min
Lesson Content

File Handling: Working with Files

Python makes it easy to read from and write to files. This is essential for storing data, reading configuration files, and processing data files.

Opening Files

Use the open() function with a context manager (with statement):

# Open file for reading
with open('file.txt', 'r') as f:
    content = f.read()
    print(content)

# File modes: # 'r' - Read (default) # 'w' - Write (overwrites existing) # 'a' - Append (adds to end) # 'x' - Create (fails if exists) # 'b' - Binary mode (add to other modes)

Reading Files

# Read entire file
with open('file.txt', 'r') as f:
    content = f.read()  # Entire file as string

# Read line by line with open('file.txt', 'r') as f: for line in f: print(line.strip()) # strip() removes newline
# Read all lines into a list with open('file.txt', 'r') as f: lines = f.readlines() # List of lines

Writing Files

# Write to file (overwrites)
with open('output.txt', 'w') as f:
    f.write('Hello, World!\n')
    f.write('Second line\n')

# Append to file with open('output.txt', 'a') as f: f.write('Appended line\n')

Working with JSON Files

import json

# Write JSON data data = {"name": "Alice", "age": 25} with open('data.json', 'w') as f: json.dump(data, f)
# Read JSON data with open('data.json', 'r') as f: data = json.load(f) print(data)

Error Handling with Files

try:
    with open('file.txt', 'r') as f:
        content = f.read()
except FileNotFoundError:
    print("File not found!")
except PermissionError:
    print("Permission denied!")
finally:
    print("File operation complete")

Best Practices

  • āœ… Always use with statement (auto-closes file)
  • āœ… Handle file errors gracefully
  • āœ… Use appropriate file modes
  • āœ… Close files when done (with statement does this automatically)
Example Code

Practice reading and writing files.

# Write data to a file
with open('info.txt', 'w') as f:
    f.write('Name: John\n')
    f.write('Language: Python\n')
    f.write('Level: Beginner\n')

# Read and print the file
with open('info.txt', 'r') as f:
    content = f.read()
    print(content)

Expected Output:

Name: John
Language: Python
Level: Beginner
Study Tips
  • •Read the theory content thoroughly before practicing
  • •Review the example code to understand key concepts
  • •Proceed to the Practice tab when you're ready to code