Examples
- How to Create Directory in Python? New and If Not Exists
- How to Change Directory in Python? Change Current Working Directory
- How to Get Current Working Directory in Python?
- How to Remove Directory in Python? (Empty & With Files)
- How to Copy Directory in Python? Program With Examples
- How to Open Directory in Python? Program & Example
- How to Read All Files in Directory in Python? (All Types of Files)
- How to Copy File in Python From One Directory to Another? (With and Without shutil)
- Python File Append Program (Append to File)
- How to Read Text File in Python Line by Line? (3 Ways)
- How to Get File Name From File Path in Python?
- Get Number of Lines in File in Python (Line Count)
- How to Get Size of File in Python? (File Size Program)
Python File Append Program (Append to File)
Appending data to a file is a common requirement when working with file systems in Python. Whether it's logging information, updating configuration files, or maintaining a record of events, the ability to append data to an existing file is a crucial aspect of file handling. In this post, we will learn how to append to a file in Python, allowing you to efficiently add content to files without overwriting their existing contents.
Python provides simple and powerful methods to handle file operations, and appending data is no exception. Using the appropriate file handling techniques, you can open a file in append mode, ensuring that any new data is written to the end of the file.
Append to File in Python
To append to a file in Python, you can use the built-in open() function with the mode parameter set to 'a' (append mode). This allows you to open the file in a way that any data you write will be appended to the end of the file, rather than overwriting its contents.
Here's an example program:
Code
def append_to_file(file_path, content):
try:
with open(file_path, 'a') as file:
file.write(content)
print("Content appended to the file.")
except IOError as e:
print(f"Unable to append to file. {e}")
# Example usage
file_path = "/path/to/file.txt"
content = "This is the new content to be appended."
append_to_file(file_path, content)
Output
Content appended to the file.
Explanation
In the above program, the append_to_file() function takes the file path and the content to be appended as arguments. It uses the open() function with the 'a' mode to open the file in append mode.
Then, it writes the content to the file using the write() method of the file object. If the operation is successful, it prints a success message. If an IOError occurs, it catches the exception and prints an error message.