Tutorial Material

File I/O

Share to
Python File I/O

This section covers basic input/output operations in Python 3.

Output with print()

print() converts values to text and writes to standard output.

print("Python is a great programming language")
print("A", "B", "C", sep="-")

Keyboard Input with input()

In Python 3, input() always returns a string.

# Simulate values that usually come from input()
name = "Alice"
age = 24
print(f"Hello {name}, next year you are {age + 1}")

Reading Files

Use with to ensure files are closed automatically.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("learn python\n")
    f.write("File I/O is important\n")

with open("notes.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

Common read methods:

Writing Files

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("learn python\n")
    f.write("File I/O is important\n")

File modes:

Safe JSON I/O Example

import json

data = {"name": "Alice", "level": "intermediate"}

with open("user.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

with open("user.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)

print(loaded)