In this example, you will learn to copy the content of a file to another file using Python.
To understand this example, you should have the knowledge of the following Python programming topics:
Using shutil module
from shutil import copyfile
copyfile("/root/a.txt", "/root/b.txt")
The first parameter of copyfile() is the path of the source file and the second parameter is the path of the destination file. The content of the destination file is replaced with the content of the source file.
There are other methods copy(), cop2(), and copyfileobj() which serve the same purpose with some metadata changes.
| Method | Preserves Permissions | Supports Directory as Destination | Copies Metadata | Supports file object |
|---|---|---|---|---|
| copy() | Yes | Yes | No | No |
| copyfile() | No | No | No | No |
| copy2() | Yes | Yes | Yes | No |
| copyfileobj() | No | No | No | Yes |
Related posts:
Python Program to Get Line Count of a File
Python String isspace()
Python len()
Python Program to Print Output Without a Newline
Python Strings
Python Program to Represent enum
Python String translate()
Python Dictionary copy()
Python Program to Measure the Elapsed Time in Python
Python Program to Make a Simple Calculator
Python String expandtabs()
Python print()
Python sum()
Python divmod()
Python String upper()
Python classmethod()
Python Program to Find Sum of Natural Numbers Using Recursion
How to get current date and time in Python?
Python int()
Python String splitlines()
Python Program to Create a Long Multiline String
Python bytearray()
Python Program to Calculate the Area of a Triangle
Python String zfill()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python String count()
Python Dictionary
Python Program to Solve Quadratic Equation
Python List sort()
Python Program to Find the Square Root
Python Program to Swap Two Variables
Python Keywords and Identifiers