The open()
function in Python is used to create file objects, which allow us to read, write, or manipulate files.
🔹 Syntax of open()
file_object = open("filename", mode)
"filename"
: Name of the file (with extension, e.g.,"data.txt"
).mode
: Specifies how the file should be opened (read, write, append, etc.).
🔹 File Open Modes
Mode | Description |
---|---|
'r' |
Read (default mode). Fails if the file does not exist. |
'w' |
Write. Creates a new file or overwrites an existing file. |
'a' |
Append. Adds new content at the end of the file. |
'x' |
Create. Fails if the file already exists. |
'b' |
Binary mode. Used for images, videos, etc. (e.g., 'rb' , 'wb' ). |
't' |
Text mode (default). Used for text files. |
'+' |
Read and write mode (e.g., 'r+' , 'w+' , 'a+' ). |
🔹 Creating a File Object
1️⃣ Opening a File for Writing ('w'
)
file = open("example.txt", "w") # Opens a file in write mode
file.write("Hello, Python!\n") # Writes data to the file
file.close() # Closes the file
✅ If "example.txt"
does not exist, it creates it.
⚠️ If it exists, it overwrites the content.
2️⃣ Opening a File for Reading ('r'
)
file = open("example.txt", "r") # Opens file in read mode
content = file.read() # Reads the file
print(content) # Prints the content
file.close() # Closes the file
✅ If the file does not exist, it raises a FileNotFoundError
.
3️⃣ Opening a File for Appending ('a'
)
file = open("example.txt", "a") # Opens file in append mode
file.write("Adding more text!\n") # Appends text to the file
file.close()
✅ New content is added at the end of the file without deleting existing data.
4️⃣ Opening a File in Binary Mode ('rb'
, 'wb'
)
Used for images, videos, or binary files.
file = open("image.jpg", "rb") # Opens an image file in binary read mode
data = file.read()
file.close()
5️⃣ Using with open()
(Recommended)
Using with open()
, the file automatically closes after execution.
with open("example.txt", "r") as file:
content = file.read()
print(content) # No need to call file.close()
✅ Best Practice: Prevents errors due to forgetting file.close()
.
🔹 Checking if a File Exists Before Opening
import os
if os.path.exists("example.txt"):
with open("example.txt", "r") as file:
print(file.read())
else:
print("File not found!")
🔹 Opening a File for Both Reading and Writing ('r+'
, 'w+'
, 'a+'
)
Read & Write ('r+'
)
with open("example.txt", "r+") as file:
content = file.read()
file.write("\nNew line added!")
✅ Reads existing content before writing.
Write & Read ('w+'
)
with open("example.txt", "w+") as file:
file.write("Overwriting everything!\n")
file.seek(0) # Moves cursor to the beginning
print(file.read()) # Reads the updated content
⚠️ Overwrites the entire file.
🔹 Summary
Mode | Usage |
---|---|
'r' |
Read file (error if file doesn’t exist). |
'w' |
Write file (creates/overwrites file). |
'a' |
Append file (adds new content). |
'x' |
Create file (error if file exists). |
'b' |
Binary mode ('rb' , 'wb' for images, videos). |
'+' |
Read + Write ('r+' , 'w+' , 'a+' ). |
Would you like a real-world example, like a log file system? 🚀
Leave a Reply