Python Program to Copy the Contents of a File
Beginner · File handling
Copying a file means reading everything from one file, the source, and writing it to another, the destination. This program copies a text file line by line, prints the copy, and then compares the two files to check that the copy is exact.
Program
Copied original.txt to copy.txt Contents of copy.txt: Line one of the original file Line two has some numbers: 10, 20, 30 Line three is the last line The two files are identical: True
How it works
- The program writes a three-line file first, so there is something to copy.
- One
withstatement can open two files at once:srcfor reading anddstfor writing. for line in srcreads one line at a time anddst.write(line)writes it unchanged, newline included, so even a very large file is copied without loading all of it.- Reading both files again and comparing their text with
==confirms the copy is exact.
Other ways to write it
Using shutil.copyfile()
backup.txt says: Copied with one function call
shutil.copyfile() from the standard library copies any file, text or binary, in one line. Use it in real programs, and the loop when your teacher asks you to read and write the file yourself.
Copying a binary file
Bytes in the copy: [0, 1, 2, 3, 250, 255]
Opening both files in binary mode, "rb" and "wb", copies the bytes exactly as they are, which is how you copy images, PDFs and other files that are not plain text.
Try it yourself
Change the loop so it writes line.upper() instead of line, making a copy in capital letters.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Copy Lines Without the Letter 'a' to Another File
- Write to a File
- Read a File Line by Line
- Append Text to a File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises