Khalsa Labs

3 Ways To Copy File with Python

These are Simple 3 Ways To Copy File with Python using built-in functions or Native logic. You can copy single or multiple files with use of Python.

Let’s see how easy it is to copy file with Python

Assume you have to copy ‘ testfile.txt ‘ from ‘ oldFolder ‘ to ‘ newFolder ‘

1st Way: Use ‘ shutil ‘ – Python’s built-in library to copy . 

import shutil
shutil.copy("oldFolder/testfile.txt", newFolder/")

“above two lines are sufficient for copy file from one directory to other Efficiently”

2nd Way: Use Native Method For File Handling

file1 = open("oldFolder/testfile.txt","r")
file2 = open("newFolder/testfile.txt","w")
file2.write(file1.read())
file1.close()
file2.close()

“above code is easy to understand, with use of native methods”

3rd Way: Use Native Methods as Single Line Code

open("newFolder/testfile.txt","w").write(open(oldFolder/testfile.txt","r").read())

“above is single line code to copy file from one path to other”

I will suggest you to use the first way, except you are not using it for some hacking purpose 🙂

The following two tabs change content below.
Python Developer and DIY lover.

want to comment ??

Your email address will not be published. Required fields are marked *