- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
Python Program to Copy Content of One File to Another
This article is created to cover some programs in Python, that copies the content of one file to another. Name of both files must be entered by user at run-time. Here are the list of programs:
- Copy Content of One File to Another without using copyfile() Method
- Using copyfile() Method
- Using with and as Keywords
- Shortest Python Code to Copy File's Content
Things to Do before Program
Since the program given below copies the content of one file to another, entered by user. Therefore we've to create a file inside the current directory. Current directory means, the directory where the Python source code to copy one file to another is saved. Therefore create a file named fresherearth.txt with following content:
Hello Python! I'm a File My name is fresherearth.txt
Here is the snapshot of folder where the file and the Python source code (to copy file's content) is saved:
And here is the snapshot of opened file fresherearth.txt:
Now let's move on to the program that copies the content of file entered by user (fresherearth.txt here) to any other file, also entered by user.
Copy Content of One File to Another in Python
To copy the content of one file to another in Python, you have ask from user to enter the name of two files. The first file referred as a source, whereas the second file referred as a target file. That is, the content of source file gets copied to the target file as shown in the program given below:
The question is, write a Python program to copy one file to another entered by user at run-time. Here is its answer:
print("Enter the Name of Source File: ") sFile = input() print("Enter the Name of Target File: ") tFile = input() fileHandle = open(sFile, "r") texts = fileHandle.readlines() fileHandle.close() fileHandle = open(tFile, "w") for s in texts: fileHandle.write(s) fileHandle.close() print("\nFile Copied Successfully!")
This is the initial output produced by this Python program, asking from user to enter the name of source file. Source file is the file, of which the content gets copied to another (target) file:
Now supply inputs say fresherearth.txt (newly created file) as name of source file, press ENTER
key and then type codes.txt as name of target file, and again press ENTER
key to copy the content
of source file to the target file.
If target file doesn't exist in the current directory, then a new file with same name gets created and the content of source file gets copied. Here is its sample output:
After supplying exactly these inputs as shown in this sample run. A file named codes.txt gets created inside the same folder, where the source code (above program) and the file (fresherearth.txt) is saved. Here is the snapshot of the folder:
As you can see that a new file with same name as entered for the name of target file, gets created. And if you open the file codes.txt, it contains the same content as of fresherearth.txt file.
Modified Version of Previous Program
This is the modified version of previous program. This program uses try-except to print error message when anything strange happens like the source file entered by user doesn't exist.
The end= is used to skip inserting newline using print(). This program also displays the copied content if user enters y as choice.
print("Enter Source File's Name: ", end="") sfile = input() try: filehandle = open(sfile, "r") print("Enter Target File's Name: ", end="") tfile = input() texts = filehandle.readlines() filehandle.close() try: filehandle = open(tfile, "w") for s in texts: filehandle.write(s) filehandle.close() print("\nContent of \"" +sfile+ "\" gets Copied to \"" +tfile+ "\" Successfully!") print("\nWant to Display the Content of \"" +tfile+ "\" (y/n) ? ", end="") chk = input() if chk.lower()=='y': try: filehandle = open(tfile, "r") contents = filehandle.readlines() for s in contents: print(s, end="") filehandle.close() print() except IOError: print("\nError occurred while opening the file!") except IOError: print("\nError occurred while opening/creating the file!") except IOError: print("\nThe file doesn't exist!")
Here is its sample run with users inputs, fresherearth.txt as name of source file, cracker.txt as name of target file and y as input to see the copied content of target file:
Note - If you'll open the folder, you'll see another new file named cracker.txt gets created with same content.
In above program, if the statement:
filehandle = open(sfile, "r")
written as first statement inside the body of try, raises an error like when file doesn't exist, then its counterpart, that is except's statement(s) gets executed.
Copy File using copyfile() of shutil
This program uses copyfile() method to copy the content of one file to another. But before using the copyfile() method, we've to import copyfile from shutil module like shown in the program given below:
from shutil import copyfile print("Enter Source File's Name: ", end="") sfile = input() print("Enter Target File's Name: ", end="") tfile = input() copyfile(sfile, tfile) print("\nContent of \"" +sfile+ "\" gets Copied to \"" +tfile+ "\" Successfully!") print("\nWant to Display the Content of \"" +tfile+ "\" (y/n) ? ", end="") chk = input() if chk.lower()=='y': filehandle = open(tfile, "r") print(filehandle.read()) filehandle.close()
This program works in similar way as of previous program. Above program can also be created by replacing the following two statements:
from shutil import copyfile copyfile(sfile, tfile)
with
import shutil shutil.copyfile(sfile, tfile)
Copy File using with and as Keywords
This program uses with and as keywords to do the same job of copying the content of one file to another.
print("Enter Name of Source and Target File: ", end="") sfile = input() tfile = input() with open(sfile, "r") as shandle: with open(tfile, "w") as thandle: for line in shandle: thandle.write(line) shandle.close() thandle.close() print("\nFile Copied!") print("\nWant to Display the Content (y/n) ? ", end="") chk = input() if chk.lower()=='y': with open(tfile, "r") as fhandle: for line in fhandle: print(line, end="") fhandle.close() print()
Here is its sample run with user inputs, fresherearth.txt (source file's name), file.txt (target file's name), and y (choice to see the content):
Shortest Python Code to Copy File's Content
This is the shortest Python code to copy file's content with user-input.
sfile = input() tfile = input() with open(sfile, "r") as shandle: with open(tfile, "w") as thandle: for line in shandle: thandle.write(line)
Same Program in Other Languages
« Previous Program Next Program »