How To Copy File with Python - 3 Ways To Copy Files

How To Copy File with Python - 3 Ways To Copy Files

Copying a file with Python is an easy task if you know how to use default copy functions in Python. Here are 3 ways to copy files using our How to Copy File with Python. Shutil library is a default copy library in 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 simple code.

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 🙂