Why File Handling Matters
Real programs need to read from and write to files — logs, configuration, datasets, reports. Python makes this simple with the built-in open() function.
Opening a File
file = open("data.txt", "r") # open in read mode
content = file.read()
file.close() # always close the file when done
File Modes
| Mode | Meaning |
|---|---|
| "r" | Read (default) — file must exist |
| "w" | Write — creates the file, overwrites if it exists |
| "a" | Append — adds to the end of the file |
| "x" | Create — fails if the file already exists |
| "rb" / "wb" | Read/Write in binary mode |
The with Statement (Recommended)
Using with automatically closes the file for you — even if an error occurs. This is the recommended way to handle files in Python:
with open("data.txt", "r") as file:
content = file.read()
print(content)
# file is automatically closed here
Reading a File
with open("data.txt", "r") as file:
print(file.read()) # read entire file as one string
with open("data.txt", "r") as file:
print(file.readline()) # read a single line
with open("data.txt", "r") as file:
for line in file: # loop through file line by line
print(line.strip())
Writing to a File
with open("notes.txt", "w") as file:
file.write("Learning Python at CodingNow\n")
file.write("File handling is easy!\n")
Careful: mode "w" completely overwrites the existing file content. Use "a" if you want to add to it instead.
Appending to a File
with open("notes.txt", "a") as file:
file.write("Adding one more line.\n")
Checking If a File Exists
import os
if os.path.exists("data.txt"):
print("File found!")
else:
print("File does not exist.")
Key Takeaways
- Always prefer
with open(...) as file:— it closes the file automatically - Mode
"w"overwrites a file; mode"a"appends to it - Loop through a file object directly to read it line by line efficiently