Writing Files
Using open() with "w" mode, you can create or overwrite files. The with statement ensures files are closed properly.
filename = "sample.txt"
with open(filename, "w", encoding="utf-8") as file:
file.write("Hello file handling!\n")
file.write("This is a second line.\n")
print("Wrote to", filename)
Reading Files
open() with "r" mode lets you read files. read() loads the entire content, while iterating reads line by line.
with open(filename, "r", encoding="utf-8") as file:
content = file.read()
print("File content:")
print(content)
Line‑by‑Line Reading
Reading files line by line is efficient for large files, as it avoids loading everything into memory at once.
with open(filename, "r", encoding="utf-8") as file:
for line in file:
print("Line:", line.strip())
My take
File handling allows Python to interact with the outside world. You can:
- Write data to files for storage.
- Read files to process information.
- Handle files line by line for efficiency. This skill is essential for building applications that log activity, store user data, or process text files.