Module 3 of 5 · Python Fundamentals Part 2 · Beginner

Working with Files

Duration: 5 min

File I/O in Python

File I/O (Input/Output) allows you to read from and write to files. Python provides built-in functions to handle file operations. Always remember to close files after using them or use the 'with' statement for automatic cleanup.

Reading Files

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

# Method 2: Read line by line
with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

# Method 3: Read all lines into a list
with open("data.txt", "r") as file:
    lines = file.readlines()
    print(lines)

Try it in Google Colab: Open in Colab

Line 1
Line 2
Line 3

Writing Files

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

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

# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
    file.writelines(lines)
File created and written successfully

File Modes

• 'r': Read (default)
• 'w': Write (overwrites existing content)
• 'a': Append (adds to existing content)
• 'x': Create (fails if file exists)
• 'b': Binary mode (e.g., 'rb', 'wb')
• '+': Read and write (e.g., 'r+', 'w+')

Working with CSV Files

import csv

# Writing CSV
data = [
    ["Name", "Age", "City"],
    ["Alice", 25, "New York"],
    ["Bob", 30, "London"],
    ["Charlie", 35, "Paris"]
]

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

# Reading CSV
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
['Name', 'Age', 'City']
['Alice', '25', 'New York']
['Bob', '30', 'London']
['Charlie', '35', 'Paris']

💡 Tip: Always use the 'with' statement when working with files. It automatically closes the file even if an error occurs.

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

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

← Previous Continue interactively → Next →

Related Courses