Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are the modes a file can be opened using Python?
When working with files in Python, it's crucial to understand the different modes in which files can be opened. Each mode defines specific operations you can perform − whether reading, writing, appending, or handling binary data. Following are the common file modes in Python.
- Read Mode: 'r'
- Write Mode: 'w'
- Binary Mode: 'b'
- Append Mode: 'a'
Read Mode: 'r'
The default mode for opening files in Python is read mode ('r'). This allows you to read the contents of a file without modifying it. If the file does not exist, it raises a FileNotFoundError.
Reading a File
In the following example, we create sample content and demonstrate reading it using the 'read()' method ?
# Create sample content
content = "Hello, World!\nThis is a sample file."
# Write to file first
with open('example.txt', 'w') as file:
file.write(content)
# Now read the file
def read_file_content(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print(f"The file '{file_path}' does not exist.")
read_file_content('example.txt')
Hello, World! This is a sample file.
Reading Line by Line
You can iterate over each line in the file, which is memory-efficient for large files ?
def read_file_line_by_line(file_path):
try:
with open(file_path, 'r') as file:
for line in file:
print(line.strip())
except FileNotFoundError:
print(f"The file '{file_path}' does not exist.")
read_file_line_by_line('example.txt')
Hello, World! This is a sample file.
Using 'readlines()' Method
The readlines() method reads all lines into a list ?
def read_file_lines(file_path):
try:
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
except FileNotFoundError:
print(f"The file '{file_path}' does not exist.")
read_file_lines('example.txt')
Hello, World! This is a sample file.
Write Mode: 'w'
The write mode ('w') is used to create or overwrite a file. If the file already exists, it truncates the file, removing all existing data.
Writing to a File
Here we open a file in write mode and write content to it ?
def write_to_file(file_path, content):
try:
with open(file_path, 'w') as file:
file.write(content)
print("Data written successfully!")
except Exception as e:
print(f"An error occurred: {e}")
write_to_file('output.txt', 'Hello, World!\nThis is new content.')
Data written successfully!
Writing Multiple Lines
You can write multiple lines by iterating over a list of strings ?
def write_multiple_lines(file_path, lines):
try:
with open(file_path, 'w') as file:
for line in lines:
file.write(line + '\n')
print("Multiple lines written successfully!")
except Exception as e:
print(f"An error occurred: {e}")
write_multiple_lines('output.txt', ['First line.', 'Second line.', 'Third line.'])
Multiple lines written successfully!
Binary Mode: 'b'
The Binary mode ('b') is used to read or write binary files such as images, audio files, or any non-textual data. It can be combined with read ('rb') or write ('wb') modes.
Writing a Binary File
Here we create and write binary data to a file ?
def write_binary_file(file_path, binary_content):
try:
with open(file_path, 'wb') as file:
file.write(binary_content)
print("Binary data written successfully!")
except Exception as e:
print(f"An error occurred: {e}")
binary_data = bytes([0, 1, 2, 3, 255])
write_binary_file('output.bin', binary_data)
Binary data written successfully!
Reading a Binary File
Now we can read the binary file we just created ?
def read_binary_file(file_path):
try:
with open(file_path, 'rb') as file:
binary_data = file.read()
print(f"Binary data: {binary_data}")
print(f"As list: {list(binary_data)}")
except FileNotFoundError:
print(f"The file '{file_path}' does not exist.")
read_binary_file('output.bin')
Binary data: b'\x00\x01\x02\x03\xff' As list: [0, 1, 2, 3, 255]
Append Mode: 'a'
The Append mode ('a') allows you to add new data to an existing file without removing its current contents. If the file does not exist, it will create a new file.
Appending to a File
Here we append content to an existing file ?
def append_to_file(file_path, content):
try:
with open(file_path, 'a') as file:
file.write(content + '\n')
print("Data appended successfully!")
except Exception as e:
print(f"An error occurred: {e}")
append_to_file('output.txt', 'This is additional content.')
Data appended successfully!
Appending with Timestamp
You can append content with timestamps for logging purposes ?
from datetime import datetime
def append_with_timestamp(file_path, content):
try:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(file_path, 'a') as file:
file.write(f"{timestamp}: {content}\n")
print("Data with timestamp appended successfully!")
except Exception as e:
print(f"An error occurred: {e}")
append_with_timestamp('output.txt', 'Content with timestamp.')
Data with timestamp appended successfully!
Common File Mode Combinations
| Mode | Description | Creates File? | Truncates? |
|---|---|---|---|
| 'r' | Read only | No | No |
| 'w' | Write only | Yes | Yes |
| 'a' | Append only | Yes | No |
| 'r+' | Read and write | No | No |
| 'w+' | Write and read | Yes | Yes |
Conclusion
Understanding file modes is essential for effective file handling in Python. Use 'r' for reading, 'w' for writing (overwrites), 'a' for appending, and add 'b' for binary operations. Always use the with statement to ensure proper file closure and error handling.
