Use open() with modes: "r", "w", "a", "x".
Context Manager
The with statement ensures files are properly closed.
JSON Module
json.dump() and json.load() for structured data.
Use open() with modes: "r", "w", "a", "x".
The with statement ensures files are properly closed.
json.dump() and json.load() for structured data.
with open("file.txt", "r") as f: content = f.read() with open("out.txt", "w") as f: f.write("Hello ") import json data = {"name": "Alice"} with open("data.json", "w") as f: json.dump(data, f)
# Writing files with open("notes.txt", "w") as f: f.write("Line 1 ") f.write("Line 2 ") # Reading files with open("notes.txt", "r") as f: content = f.read() print("Content:", repr(content)) # Read line by line with open("notes.txt", "r") as f: for line in f: print("Line:", line.strip()) # Append with open("notes.txt", "a") as f: f.write("Line 3 ") # With block auto-closes the file!
# Write to file with open("example.txt", "w") as f: f.write("Hello, World! ") f.write("Line two ") # Read from file with open("example.txt", "r") as f: content = f.read() print(content) # Read line by line with open("example.txt", "r") as f: for line in f: print(line.strip())
Copy a file converting text to uppercase.
with open("src.txt") as s:
with open("dst.txt","w") as d:
d.write(s.read().upper())
Why use the with statement?
Ensures files are closed automatically.
read() returns entire file. readline() returns one line. readlines() returns list of lines.