While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it's opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows:
- Append Only (‘a’): Open the file for writing.
- Append and Read (‘a+’): Open the file for reading and writing.
These modes are ideal when you want to preserve existing content while adding more. Let's look at some examples:
Example 1: Append vs write mode.
Python
# Write mode: overwrites the file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()
# Append mode: adds to the end of the file
file1 = open("myfile.txt", "a")
file1.write("Today \n")
file1.close()
# Reading file content
file1 = open("myfile.txt", "r")
print("Output after appending:")
print(file1.read())
file1.close()
# Write mode again: overwrites previous content
file1 = open("myfile.txt", "w")
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt", "r")
print("Output after overwriting:")
print(file1.read())
file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is LondonToday
Output of Readlines after writing
Tomorrow
Explanation:
- Using "w" replaces the file content entirely.
- Using "a" preserves the existing content and appends new data to the end.
- This demonstrates how "a" and "w" behave differently.
Example 2: Append from a New Line
In the above example of file handling, it can be seen that the data is not appended from the new line. This can be done by writing the newline '\n' character to the file.
Python
# Initial file content
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()
# Appending with and without newline
file1 = open("myfile.txt", "a")
file1.write("\n")
file1.write("Today")
file1.write("Tomorrow")
file1.close()
# Read updated content
file1 = open("myfile.txt", "r")
print("Output after appending:")
print(file1.read())
file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
TodayTomorrow
Explanation:
- \n ensures "Today" starts on a new line.
- Without \n, "Tomorrow" continues right after "Today".
Note: ‘\n’ is treated as a special character of two bytes.
Example 3: Using With statement in Python
with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement.
Python
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# Writing to file
with open("myfile.txt", "w") as file1:
file1.write("Hello \n")
file1.writelines(L)
# Appending data
with open("myfile.txt", "a") as file1:
file1.write("Today")
# Reading file
with open("myfile.txt", "r") as file1:
print(file1.read())
Output:
Hello
This is Delhi
This is Paris
This is London
Today
Explanation:
- The with block ensures file1.close() is called automatically.
- It’s a best practice for file handling to avoid resource leaks.
Note: To know more about with statement click here.
Example 4: Appending File Content Using shutil
This approach uses the shutil.copyfileobj() method to append the contents of another file (source_file) to 'file.txt'. This can be useful if you want to append the contents of one file to another without having to read the contents into memory first.
Python
import shutil
# Open destination file in append-binary mode
with open("file.txt", "ab") as dest:
# Open source file in read-binary mode
with open("source_file.txt", "rb") as src:
shutil.copyfileobj(src, dest)
Explanation:
- This is useful for copying content from large files efficiently.
- Works in binary mode to preserve file format.
Related article: File Handling in Python
Similar Reads
Appending to 2D List in Python A 2D list in Python is a list of lists where each sublist can hold elements. Appending to a 2D list involves adding either a new sublist or elements to an existing sublist. The simplest way to append a new sublist to a 2D list is by using the append() method.Pythona = [[1, 2], [3, 4]] # Append a new
2 min read
Python List append() Method append() method in Python is used to add a single item to the end of list. This method modifies the original list and does not return a new list. Let's look at an example to better understand this.Pythona = [2, 5, 6, 7] # Use append() to add the element 8 to the end of the list a.append(8) print(a)O
3 min read
How to open and close a file in Python There might arise a situation where one needs to interact with external files with Python. Python provides inbuilt functions for creating, writing, and reading files. In this article, we will be discussing how to open an external file and close the same using Python. Opening a file in Python There a
4 min read
Python - Write Bytes to File Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps:Open filePerform operationClose fileThere are four basic modes in which a file can
3 min read
Python - Append content of one text file to another Having two file names entered by users, the task is to append the content of the second file to the content of the first file with Python. Append the content of one text file to anotherUsing file objectUsing shutil moduleUsing fileinput moduleSuppose the text files file1.txt and file2.txt contain th
3 min read