File Handling in Python
Open, read and write text and binary files with the with statement.
Beginner
with open("log.csv", "w", newline="") as f:
f.write("time,voltage\n")
f.write("0,3.3\n")
with open("log.csv") as f:
for line in f:
print(line.strip())
with closes the file automatically, even if an error occurs. Modes: "r" read, "w" write (overwrites), "a" append, add "b" for binary. For CSV and JSON use the csv and json modules; for paths use pathlib.Path.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.