Skip to content
Python

File Read/Write

Various ways to read and write files.

By EZ4Code Team
fileio

Code

# Read entire file
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()

# Read line by line
with open("file.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

# Write file
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("Hello World\n")

# Append write
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("new log\n")

Explanation

Uses the with statement to automatically manage file resources; specifying encoding is recommended.

More Python Snippets