Python File Handling Techniques
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 231 wordsLearn how to handle files in Python, including reading from and writing to files, file modes, and context managers.
File handling is a crucial skill in Python. This guide covers how to read from and write to files, file modes, and using context managers for better resource management.
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
with open("example.txt", "r") as file:
chunk = file.read(100)
while chunk:
print(chunk)
chunk = file.read(100)
with open("example.txt", "w") as file:
file.write("Hello, World!")
with open("example.txt", "a") as file:
file.write("\nAppend this line")
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
Understanding different file modes.
"r"
: Read (default)"w"
: Write (truncates file)"a"
: Append"r+"
: Read and writeUsing context managers ensures files are properly closed.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Context managers can also handle custom cleanup actions.
class CustomOpen:
def __init__(self, filename, mode):
self.file = open(filename, mode)
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
with CustomOpen("example.txt", "r") as file:
content = file.read()
print(content)
Effective file handling is essential for many Python applications. Practice reading from and writing to files, and use context managers to manage resources efficiently.