Copying a file with Python is an easy task if you know how to use default copy functions in 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
“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 🙂