Module 10 of 15 · Python for AI — Complete Beginner Course · Beginner

File Handling and I/O

Duration: 5 min

File handling is essential for working with data. You'll read data from files, process it, and write results back to files.

Learn more: https://docs.python.org/3/tutorial/

Reading Files

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

# Read line by line
with open('data.txt', 'r') as f:
    for line in f:
        print(line.strip())  # strip() removes newline

# Read all lines into a list
with open('data.txt', 'r') as f:
    lines = f.readlines()
    print(lines)

Try it in Google Colab: Open in Colab

Writing Files

# Write to file (overwrites if exists)
with open('output.txt', 'w') as f:
    f.write("Hello, World!\n")
    f.write("This is line 2\n")

# Append to file
with open('output.txt', 'a') as f:
    f.write("This is appended\n")

# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as f:
    f.writelines(lines)

Working with CSV Files

import csv

# Read CSV
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)  # Each row is a list

# Read CSV as dictionaries
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)  # Each row is a dict

# Write CSV
with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', 25, 'NYC'])
    writer.writerow(['Bob', 30, 'LA'])

💡 Tip: Always use 'with' statement for file operations. It automatically closes the file.

❓ What does 'a' mode do when opening a file?

❓ What is a best practice when working with File Handling and I/O?

💡 Tip: Pro Tip: Master File Handling and I/O thoroughly before moving to advanced topics. This foundation is crucial for writing professional Python code.

← Previous Continue interactively → Next →

Related Courses