The open()
function opens a file for reading, writing, or appending. It’s useful for reading files, writing logs, processing large data, and managing file storage.
Example
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read file content
file.close()
print(content)
This opens, reads, and closes the file.
Syntax
open(file, mode="r", encoding=None)
- file → The name (or path) of the file to open.
- mode (optional) → Specifies read (
r
), write (w
), append (a
), etc. - encoding (optional) → Commonly
"utf-8"
for text files. - Returns → A file object.
1. Reading a File (r
Mode)
with open("data.txt", "r") as file:
print(file.read()) # Reads the entire file
The with
statement automatically closes the file.
2. Writing to a File (w
Mode)
with open("data.txt", "w") as file:
file.write("Hello, World!")
Overwrites existing content.
3. Appending to a File (a
Mode)
with open("data.txt", "a") as file:
file.write("\nNew line added!")
Adds content without deleting previous data.
4. Reading a File Line by Line
with open("data.txt", "r") as file:
for line in file:
print(line.strip()) # Remove extra spaces
Efficient for large files.
5. Reading a File as a List
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
Stores each line as a list item.
6. Handling File Not Found Errors
try:
with open("missing.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found!")
Prevents program crashes when files are missing.
File Modes
Mode | Description |
---|---|
"r" |
Read (default) |
"w" |
Write (creates/overwrites) |
"a" |
Append (adds to existing) |
"x" |
Create (fails if file exists) |
"rb" |
Read in binary mode |
"wb" |
Write in binary mode |
"r+" |
Read & write (keeps content) |
"w+" |
Read & write (overwrites) |
Key Notes
- ✔ Reads, writes, and appends to files.
- ✔
with open()
ensures files are closed properly. - ✔ Use
"utf-8"
encoding for text files. - ✔ Handle missing files with
try-except
.
By using open()
, you can manage files efficiently, making it essential for file processing, logging, and data storage. 🚀