How to Append Contents of One File in Python


In this example we will show how to append the contents of one file to another in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fname1 = input("Please input the orginal file name: ")
fname2 = input("Please input the new file name: ")
sourceFile = open(fname1, "r")
data1 = sourceFile.read()
sourceFile.close()
outFile = open(fname2, "a")
outFile.write("\n")
outFile.write(data1)
outFile.close()
Content of test1.txt: 
Python is an easy to learn
powerful programming language

Content of test3.txt: 
Python7 is an easy to learn5
powerful8 programming language25

Output:

Please input the orginal file name: test1.txt
Please input the new file name: test3.txt

The contents of the test3.txt file:


Python7 is an easy to learn5
powerful8 programming language25
Python is an easy to learn
powerful programming language

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments