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.
When the file is opened in append mode in Python, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Example 1: Python program to illustrate Append vs write mode.
Python3
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt", "r")
print("Output of Readlines after writing")
print(file1.read())
print()
file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is LondonToday
Output of Readlines after writing
Tomorrow
Example 2: Append data 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.
Python3
# Python program to illustrate
# append from new line
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()
# Append-adds at last
# append mode
file1 = open("myfile.txt", "a")
# writing newline character
file1.write("\n")
file1.write("Today")
# without newline character
file1.write("Tomorrow")
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
TodayTomorrow
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. The with statement itself ensures proper acquisition and release of resources.
Python3
# Program to show various ways to
# append data to a file using
# with statement
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# Writing to file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
# Appending to file
with open("myfile.txt", 'a') as file1:
file1.write("Today")
# Reading from file
with open("myfile.txt", "r+") as file1:
# Reading form a file
print(file1.read())
Output:
Hello
This is Delhi
This is Paris
This is London
Today
Note: To know more about with statement click here.
Using the shutil module:
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.
Approach:
The code uses the shutil.copyfileobj() function to copy the contents of the source_file object to a new file called file.txt. The with statement is used to open and automatically close the file, using the file object f.
Time Complexity:
The time complexity of shutil.copyfileobj() function is proportional to the size of the file being copied, as it needs to read and write every byte of the file. Therefore, the time complexity of the code is O(n), where n is the size of the source_file.
Space Complexity:
The space complexity of the code is O(1), as it does not allocate any additional memory beyond what is required for the file objects source_file and f. The shutil.copyfileobj() function copies the file contents in chunks, so it does not need to load the entire file into memory at once.
Overall, the code has a linear time complexity and constant space complexity, where the time complexity is proportional to the size of the file being copied.
Python3
import shutil
with open('file.txt', 'a') as f:
shutil.copyfileobj(source_file, f)
Similar Reads
Append to JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
2 min read
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
numpy.append() in Python
numpy.append() function is used to add new values at end of existing NumPy array. This is useful when we have to add more elements or rows in existing numpy array. It can also combine two arrays into a bigger one. Syntax: numpy.append(array, values, axis = None)array: Input array. values: The values
2 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
Convert Python File to PDF
We are tasked with converting a Python file into a PDF document. This allows you to present or store your Python code in a more accessible format. By converting the code to a PDF, you can easily share or archive it, making it more convenient to view and print in a professional, well-organized manner
3 min read
Python | Pandas Index.append()
Python is an excellent language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas are one of those packages, making importing and analyzing data much easier. Pandas Index.append() The function is used to append a single or a collection of indices
2 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
How to copy file in Python3?
Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Pyt
2 min read