File I/O di Python
Python menyediakan fungsi built-in untuk membaca dan menulis file.
Membaca File
# Cara terbaik: with statement (auto-close)
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Baca per baris
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
Menulis File
# Write (overwrite)
with open("output.txt", "w") as file:
file.write("Baris pertama\n")
file.write("Baris kedua\n")
# Append (tambah di akhir)
with open("log.txt", "a") as file:
file.write("Log entry baru\n")
JSON File
import json
# Menulis JSON
data = {"nama": "Budi", "umur": 25}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Membaca JSON
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["nama"])
CSV File
import csv
# Membaca CSV
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)