File Operations

Reading and writing files in Python

#files #io #read #write

File Operations

Read, write, and manipulate files in Python.

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())

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

Writing Files

# Write (overwrite)
with open('output.txt', 'w') as f:
    f.write("Hello World\n")
    f.write("Second line\n")

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

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

JSON Files

import json

# Read JSON
with open('data.json', 'r') as f:
    data = json.load(f)

# Write JSON
data = {'name': 'Alice', 'age': 30}
with open('output.json', 'w') as f:
    json.dump(data, f, indent=2)

Discover another handy tool from EditPDF.pro