The Wayback Machine - https://web.archive.org/web/20240926205829/https://www.geeksforgeeks.org/python-append-content-of-one-text-file-to-another/
Open In App

Python – Append content of one text file to another

Last Updated : 02 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 another

Suppose the text files file1.txt and file2.txt contain the following data.

file1.txt 
 

file1.txt

file2.txt 

Append the content of one text file to another using the file object

Enter the names of the files then open both files in read-only mode using the open() function and print the contents of the files before appending them using the read() function now close both files using the close() function. and open the first file in append mode and the second file in read mode. Append the contents of the second file to the first file using the write() function. Reposition the cursor of the files at the beginning using the seek() function. Print the contents of the appended files. and Close both files.

python3




# entering the file names
firstfile = input("Enter the name of first file ")
secondfile = input("Enter the name of second file ")
 
# opening both files in read only mode to read initial contents
f1 = open(firstfile, 'r')
f2 = open(secondfile, 'r')
 
# printing the contents of the file before appending
print('content of first file before appending -', f1.read())
print('content of second file before appending -', f2.read())
 
# closing the files
f1.close()
f2.close()
 
# opening first file in append mode and second file in read mode
f1 = open(firstfile, 'a+')
f2 = open(secondfile, 'r')
 
# appending the contents of the second file to the first file
f1.write(f2.read())
 
# relocating the cursor of the files at the beginning
f1.seek(0)
f2.seek(0)
 
# printing the contents of the files after appendng
print('content of first file after appending -', f1.read())
print('content of second file after appending -', f2.read())
 
# closing the files
f1.close()
f2.close()


Output:

Python - Append content of one text file to another

Time complexity: O(n), where n is the total number of characters in both files.
Auxiliary space: O(1), since we are not using any additional data structures and are only reading and writing to the files.

Append the content of one text file to another using the using shutil module

we first open (file1) and after it, we open (file2) we open file one in read mode and file2 in append mode then copyfileobj() the function reads data from file1 in chunks and appends it to file2 until the entire content is copied.

Python3




import shutil
 
def append_files_method2(file1_path, file2_path):
    with open(file1_path, 'r') as file1:
        with open(file2_path, 'a') as file2:
            shutil.copyfileobj(file1, file2)
 
# Example usage:
file1_path = 'file1.txt'
file2_path = 'file2.txt'
append_files_method2(file1_path, file2_path)


Output:

Python - Append content of one text file to another

Time complexity: O(n)
Auxiliary space: O(1), since we are not using any additional data structures and are only reading and writing to the files.

Append the content of one text file to another using the using fileinput Module

We here first open the target file2 in append mode. Then, by using fileinput.input(), we open the source file1 in read mode and iterate over its lines. and then for every line in file1, we write it to file2 using the write() method. This way work perfectly with large file to read and write data from one text file to another

Python3




import fileinput
 
def append_files_method3(file1_path, file2_path):
    with open(file2_path, 'a') as file2:
        with fileinput.input(files=file1_path) as file1:
            for line in file1:
                file2.write(line)
 
# Example usage:
file1_path = 'file1.txt'
file2_path = 'file2.txt'
append_files_method3(file1_path, file2_path)


Output:
 

Python - Append content of one text file to another

Time complexity: O(n), where n is the total number of characters in both files.
Auxiliary space: O(1)



Similar Reads

Python - Copy all the content of one file to another file in uppercase
In this article, we are going to write a Python program to copy all the content of one file to another file in uppercase. In order to solve this problem, let's see the definition of some important functions which will be used: open() - It is used to open a file in various modes like reading, write, append, both read and write.write() - It is used t
2 min read
Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
How to run multiple Python file in a folder one after another?
In this article, we will discuss how to run multiple python files in a folder one after another. There can be many ways to this task, here, we will discuss a few of them. For doing this program, we have to create some python files in one folder and give some names to that folder. The content inside a.py file: print("a") The content inside b.py file
3 min read
Python append to a file
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
4 min read
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 Python script. The text in JSON is done through quoted-
2 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
How to append a new row to an existing csv file?
For writing a CSV file, the CSV module provides two different classes writer and Dictwriter. Here we will discuss 2 ways to perform this task effectively. The First will be 'append a list as a new row to the existing CSV file' and second way is 'Append a dictionary as a new row to the existing CSV file.' First, let's have a look at our existing CSV
3 min read
How to Append Pandas DataFrame to Existing CSV File?
In this discussion, we'll explore the process of appending a Pandas DataFrame to an existing CSV file using Python. Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the 'a' parameter to write the DataFrame to the CSV file in append mode. Pandas DataFrame to_csv() Syntax Syntax : df.t
3 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
Python | How to copy data from one excel sheet to another
In this article, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python. For working with excel files, we require openpyxl, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. It can be installed using the following com
3 min read
How to add one polynomial to another using NumPy in Python?
In this article, Let's see how to add one polynomial to another. Two polynomials are given as input and the result is the addition of two polynomials. The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}. Let take two polynomials p(x) and q(x) then add these to get r(x) = p(x) + q(x) as
2 min read
How to subtract one polynomial to another using NumPy in Python?
In this article, let's discuss how to subtract one polynomial to another. Two polynomials are given as input and the result is the subtraction of two polynomials. The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}.Let take two polynomials p(x) and q(x) then subtract these to get r(x)
2 min read
Divide one Chebyshev series by another in Python
In this article, we will be looking at a method to divide one Chebyshev series by another in Python. A linear combination of Chebyshev polynomials is known as a Chebyshev series. Chebyshev polynomials are never formally generated. Only the coefficients are required for all calculations. In this article let's see how to divide one Chebyshev series b
3 min read
Add one Laguerre series to another in Python
In this article, we will be looking at the method to add one Laguerre series to another in Python. The product of the exponential of a matrix by a vector is computed using Laguerre polynomials and a Filtered Conjugate Residual (FCR) framework. In Python, we take the Numpy library, and use the polynomial.laguerre.lagadd() method to combine two Lague
2 min read
Divide one Hermite series by another in Python using NumPy
In this article, we are going to see how to divide one Hermite series by another in Python using NumPy. The numpy hermdiv() method helps us divide one Hermite series by another. The quotient and remainder of two Hermite series, c1 / c2, are returned. The arguments are a series of coefficients from lowest to highest order "term," for example, [1,4,3
3 min read
Multiply one Hermite series to another in Python using NumPy
In this article, we are going to see how to multiply one Hermite series to another in Python Using NumPy. The NumPy polynomial.hermite.hermmul() is used to Multiply one Hermite series by another series. The product of two Hermite series c1 * c2 is returned. The arguments are sequences of coefficients, starting with the lowest order "term" and endin
2 min read
Multiply one Chebyshev series to another in Python
In this article, we will cover how to multiply one Chebyshev series with another in Python using NumPy. Example Input: First array: [6 7 5] Second array: [4 5 6] Output: [56.5 91.5 73.5 33.5 15. ] Explanation: an array of Chebyshev series coefficients representing their product. chebyshev.chebmul method The Chebyshev polynomials in mathematics are
3 min read
Add one Hermite series to another using NumPy in Python
In this article, we will cover how to add one Hermite series to another using NumPy in Python. np.polynomial.hermite.hermadd method The numpy.polynomial.hermite.hermadd() method from the NumPy library is used to add one Hermite series to another. The sum of two Hermite series (c1 + c2) is returned. The arguments are sequences of coefficients in asc
3 min read
Copy all files from one directory to another using Python
In this article, we will discuss how to copy all files from one directory to another using Python. This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of files between directories. Method 1 : Using shutil.c
2 min read
How to import variables from another file in Python?
When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simpl
2 min read
How to import a class from another file in Python ?
In this article, we will see How to import a class from another file in Python. Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole
4 min read
Python - Call function from another file
Given a Python file, we need to call a function in it defined in any other Python file. Example: Suppose there is a file test.py which contains the definition of the function displayText(). #test.py>def displayText(): print( "Geeks 4 Geeks!")We need to call the function displayText() in any other Python file such that wherever we call displayTex
5 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 together. In the case of a collection of indices,
2 min read
Python | Pandas TimedeltaIndex.append()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.append() function appends a collection of index options together. More than one index object can be appended at a
2 min read
Python | Pandas Series.append()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.append() function is used to concatenate two or more series object. Syntax: Ser
4 min read
Difference Between '+' and 'append' in Python
Using '+' operator to add an element in the list in Python: The use of the '+' operator causes Python to access each element of that first list. When '+' is used a new list is created with space for one more element. Then all the elements from the old list must be copied to the new list and the new element is added at the end of this list. Example:
3 min read
Python - Append List every Nth index
Given 2 list, append list to the original list every nth index. Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = ['G', 'F', 'G'], N = 3 Output : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8] Explanation : List is added after every 3rd element.Input : test_list = [3, 7, 8, 2, 1, 5, 8, 9], app_list = ['G', 'F', 'G'], N = 4 O
5 min read
Difference between Append, Extend and Insert in Python
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their crea
3 min read
How to append a list as a row to a Pandas DataFrame in Python?
Prerequisite: Pandas DataFrame In this article, We are going to see how to append a list as a row to a pandas dataframe in Python. It can be done in three ways: Using loc[]Using iloc[]Using append()Append list using loc[] methods Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame.
3 min read