
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
File Opening Modes in 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, the function 'read_file_content' takes the file path as input. It opens the file in read mode and reads its contents, which are printed to the console. If the file does not exist, an error message is displayed.
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')
Following is the output of the above code ?
Hello, World! This is a sample file.
Reading Line by Line
In the following example, the 'read_file_line_by_line' function opens the specified file in read mode and iterates over each line, printing each one after stripping any leading or trailing whitespace.
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')
Following is the output of the above code ?
Hello, World! This is a sample file
Using 'readlines()' Method
Here, the 'read_file_lines' function reads all lines of the file using the readlines() method and prints each line. It also handles the situation where the file might not exist.
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')
Following is the output of the above code ?
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
In the following example, we are going to open a specified file in write mode and write the given content to it. If the file already exists, it is overwritten.
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.')
Following is the output of the above code ?
Data written successfully!
Writing Multiple Lines
Here, the function 'write_multiple_lines' function writes multiple lines to the specified file in write mode by iterating over a list of lines.
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.'])
Following is the output of the above code ?
Multiple lines written successfully!
Writing with Exception Handling
In this example, we attempt to write content to a specified file in write mode including exception handling for potential permission or IO errors.
def safe_write_to_file(file_path, content): try: with open(file_path, 'w') as file: file.write(content) print("Data written successfully!") except (PermissionError, IOError) as e: print(f"File operation failed: {e}") safe_write_to_file('output.txt', 'New content with error handling.')
Following is the output of the above code ?
Data 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.
Reading a Binary File
In the following example, we are going to open a binary file in read mode and read its entire binary content. It prints the binary data read from the file.
def read_binary_file(file_path): try: with open(file_path, 'rb') as file: binary_data = file.read() print(binary_data) except FileNotFoundError: print(f"The file '{file_path}' does not exist.") read_binary_file('example.jpg')
Writing a Binary File
Here, we opened a specified file in write binary ('wb') mode and wrote binary content to it. For demonstration, it converts a list of integers into bytes.
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)
Following is the output of the above code ?
Binary data written successfully!
Appending to a Binary File
In the following example, the 'append_to_binary_file' function opens a binary file in append binary mode to add binary data at the end of the file without truncating its existing content.
def append_to_binary_file(file_path, binary_content): try: with open(file_path, 'ab') as file: file.write(binary_content) print("Binary data appended successfully!") except Exception as e: print(f"An error occurred: {e}") append_to_binary_file('output.bin', bytes([4, 5, 6]))
Following is the output of the above code ?
Binary data appended successfully!
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
In the following example, we opened a specified file in append mode ('a') to add new content at the end. If the file does not exist, it creates a new one.
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.')
Following is the output of the above code ?
Data appended successfully!
Appending Multiple Lines
In the following example, the 'append_multiple_lines' function appends several lines to a file by iterating through a list and writing each line, followed by a new line character.
def append_multiple_lines(file_path, lines): try: with open(file_path, 'a') as file: for line in lines: file.write(line + '\n') print("Multiple lines appended successfully!") except Exception as e: print(f"An error occurred: {e}") append_multiple_lines('output.txt', ['New line one.', 'New line two.'])
Following is the output of the above code ?
Data appended successfully!
Appending with Timestamp
In the following example, the 'append_with_timestamp' function adds a timestamp alongside the content being appended. This can be useful for logging or tracking changes.
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.')
Following is the output of the above code ?
Data with timestamp appended successfully!