The Wayback Machine - https://web.archive.org/web/20240118182408/https://www.geeksforgeeks.org/how-to-copy-file-in-python3/
Open In App
Related Articles

How to copy file in Python3?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Prerequisites: Shutil

When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Python3.

Method 1 : Using shutil library

shutil library includes a method call copyfile(). The method takes two parameters, one is source path of file and other is destination path of file. The following image includes a file with its path.

Syntax:

copyfile(source_path,destination_path)

Source Path of File

Program:

Python3




# copy a file using shutil.copyfile() method
import shutil
  
# path where original file is located
sourcePath = "c:\\SourceFolder\\gfg.txt"
  
# path were a copy of file is needed
destinationPath = "c:\\DestinationFolder\\gfgcopy.txt"
  
# call copyfile() method
shutil.copyfile(sourcePath, destinationPath)


Output:

Destination Folder

Method 2 : copying data of file into another file

Copying data of one file to another file could also create a backup of file. Suppose the data of file is as below:

Data in source file

Program:

Python3




# open source file in read mode
source = open("c:\\SourceFolder\\gfg.txt", "r")
  
# open destination file in write mode
dest = open("c:\\DestinationFolder\\gfgcopy.txt", "w")
  
# read first line
line = source.readline()
  
# read lines until reached EOF
while line:
  
    # write line into destination file
    dest.write(line)
    # read another line
    line = source.readline()
  
# close both files
source.close()
dest.close()


Output:

Destination File


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 02 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials