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:
read()-> all contentreadline()-> one linereadlines()-> list of lines
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:
"r"read"w"write (overwrite)"a"append"x"create new file- Add
"b"for binary mode ("rb","wb")
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)