Skip to content
On this page

File Handling

Reading and Writing Files:

Python provides built-in functions to read and write files.

python
# Reading and writing files
# Writing to a file
with open("data.txt", "w") as f:
    f.write("Hello, World!")

# Reading from a file
with open("data.txt", "r") as f:
    content = f.read()
    print(content)  # Output: "Hello, World!"

Working with CSV and JSON Files:

Python also supports working with CSV and JSON files using modules like csv and json.

python
# Working with CSV files
import csv

data = [
    ["Name", "Age", "Country"],
    ["Alice", 30, "USA"],
    ["Bob", 25, "Canada"],
    ["Eva", 28, "UK"]
]

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

# Working with JSON files
import json

data = {
    "name": "Alice",
    "age": 30,
    "country": "USA"
}

with open("data.json", "w") as f:
    json.dump(data, f)