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
Sort Dictionary by Value
Sort a Python dictionary by its values in descending order.
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.
Regex Matching
Perform regex matching using the re module.