This is a Python Program to append the contents of one file to another file.
The program takes the name of the file to be read from and the file to append into from the user and appends the contents of one file to another.
1. Take the name of the file to be read from and the file to append into from the user.
2. Open the file to be read and read the content of the file and store it in a variable.
3. Open the file to append the data to and write the data stored in the variable into the file.
4. Close both the files.
5. Exit.
Here is source code of the Python Program to append the contents of one file to another file. The program output is also shown below.
name1 = input("Enter file to be read from: ") name2 = input("Enter file to be appended to: ") fin = open(name1, "r") data2 = fin.read() fin.close() fout = open(name2, "a") fout.write(data2) fout.close()
1. User must enter the name of the file to be read from and the file to append into.
2. The file to be read is opened using open() function in the read mode.
3. The contents of the file read using read() function is stored in a variable and then the file is closed.
3. The file to append the data to is opened in the append mode and the data stored in the variable is written into the file.
4. The second file is then closed..
Case 1: Output: Enter file to be read from: test.txt Enter file to be appended to: test1.txt Contents of file test.txt: Appending!! Contents of file test1.txt (before appending): Original Contents of file test1.txt (after appending): Original Appending!! Case 2: Enter file to be read from: out.txt Enter file to be appended to: out1.txt Contents of file test.txt: world Contents of file test1.txt (before appending): Hello Contents of file test1.txt (after appending): Hello world
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Check Information Technology Books
- Practice Programming MCQs
- Apply for Python Internship
- Check Python Books
- Apply for Programming Internship