Do you want to improve your Python skill? Then you can try carrying out some tasks on your computer with Python. Copying and pasting files from one directory to another with Python is a fun way to do this.
In addition to being fun, it lets you read and write files quickly without getting distracted from your code. If you’re new to Python, it’s a skill you might still need to pick up one way or another. So, let’s find out how to copy files with Python through this post.
Requirements for Copying Files With Python
There are many ways to copy and paste files with Python. So, the requirement for doing it varies and depends on the method you decide to use.
While you may not need extra modules to copy files with Python, you can still use built-in libraries if you want.
For instance, if you want to use the os method, you need to import it into your code. However, one of the popular ways of copying files with Python is using the shutil library.
Let’s see how we can use these various methods to copy files with Python.
How to Copy Files Using Python’s Built-in Shutil Library
The shutil module is a built-in and powerful Python library for reading and writing files quickly in Python.
To use it, you only need to supply the full path of the source and destination files.
In essence, shutil takes this format:
shutil.copy([source directory path], [destination directory path], follow_symlinks=True)
For example, the code below uses shutil.copy() to copy a file named copy.txt from a folder called my_folder into another one named destination. It then renames the destination file as newFile.txt:
import shutil
sourceFile = "C:/Users/some_directories/my_folder/copy.txt"
destinationFile = "C:/Users/some_directories/destination/newFile.txt"
shutil.copy(sourceFile, destinationFile, follow_symlinks=True)
Note that you can write your code in any code editor of your choice. You can then run it using the command line.
However, you can also use the default Python Integrated Development Environment (IDLE) if you’re not familiar with running Python via the command line.
The shutil.copy method doesn’t copy the metadata of the source file. In essence, your machine sees the destination file as a new one entirely and gives it new metadata.
However, to copy the metadata along with the original file, use the shutil.copy2 method:
import shutil
shutil.copy2(sourceFile, destinationFile, follow_symlinks=True)
The method above preserves the original metadata of the old file in the destination file. For instance, the destination file retains the date you created the source file, its size, and other attributes.
The follow_symlinks argument is a symbolic link declaration that lets shutil follow an absolute path. Therefore you need to include it if the source and destination files are in different directories.
But if both files are in your current working directory, you don’t need to include a follow_symlinks. If you do, Python raises a syntax exception.
So, if you’re pasting the source file into your current working directory, your code should look like this:
import shutil
shutil.copy2(sourceFile, destinationFile)
In addition to using the shutil methods above, you can also use shutil.copyfile or shutil.copyfileobj.
Using shutil.copyfileobj is a bit different as it requires the built-in open function. Then, you need to read and write binary by including the “rb” and “wb” arguments.
Let’s see how the shutil.copyfileobj method works using the same directories we used previously:
import shutil
sourceFilePath = open("C:/Users/some_directories/my_folder/copy.txt", "rb")
destinationFilePath = open("C:/Users/some_directories/destination/newFile.txt", "wb")
shutil.copyfileobj(sourceFilePath, destinationFilePath)
Note that shutil.copyfileobj() doesn’t require the follow_symlinks argument.
However, shutil.copyfile() works pretty the same way .copy and .copy2 does. They only differ insignificantly in their internal functions.
To use the shutil.copyfile() method:
import shutil
sourceFilePath = "C:/Users/some_directories/my_folder/copy.txt"
destinationFilePath = "C:/Users/some_directories/destination/newFile.txt"
shutil.copyfile(sourceFilePath, destinationFilePath)
How to Copy Files With the os Module
The os module uses two built-in methods to copy files; os.system() and os.popen() methods.
The os.system() method allows you to imitate the command line environment.
However, a shortcoming of os methods is that they only copy files within your current working directory.
To use the os.system() method on Windows:
import os
os.system('copy source.txt destination.txt)
You can also use the built-in xcopy Windows terminal command:
import os
os.system('xcopy source.txt destination.txt)
To use the os.system method on Linux, replace copy with cp:
import os
os.system('cp source.txt destination.txt)
How to Copy Files Using the os.popen Method
To use this method, replace os.system() with os.popen().
On Windows, use:
import os
os.popen('copy source.txt destination.txt)
As we did with os.system(), replace copy with cp to use this method on Linux:
import os
os.popen('cp source.txt destination.txt)
How to Copy Files With Python’s subprocess Module
In addition to the above methods, you can also use the subprocess() library to copy files in Python:
import subprocess as sp
sp.call("copy sourceFile destinationFile", shell=True)
However, on Linux, use:
import subprocess as sp
sp.call("cp sourceFile destinationFile", shell=True)
The subprocess library also uses subprocess.check_out() method. It works the same way subprocess.call() does:
import subprocess as sp
sp.check_out("copy sourceFile destinationFile", shell=True)
On Linux, replace copy with cp:
import subprocess as sp
sp.check_out("cp sourceFile destinationFIle", shell=True)
However, like the os methods, subprocess methods only work with files in your current working directory.
Note: You can also copy files into a folder if it’s in the same working directory as the source file. All you need to do is replace the destination filename with the name of the destination folder. However, ensure that the destination folder and the source file are in your current working directory.
How to Copy Files in Python Without Using Libraries
You can also copy files in Python without depending on any library. Like the shutil method, you only need the full paths of the source and destination directories.
Here’s how to achieve this:
sourcePath = "C:/Users/source_directories/my_folder/copy.txt"
destinationPath = "C:/Users/some_directories/destination_directories/newFile.txt"
with open(sourcePath, "rb") as read:
with open(destinationPath, "wb") as myfile:
myfile.write(read.read())
To make the code reusable, you can modify it into a function:
def copyFile(source=None, destination=None):
if not (source and destination)==None:
with open(source, "rb") as read:
with open(destination, "wb") as myfile:
myfile.write(read.read())
else:
print("Please enter the source and destination paths")
copyFile(sourcePath, destinationPath)
That’s it. You just made a reusable file copier with Python without using any library.
Keep Automating Tasks With Python
In addition to helping you stay focused on your code while building projects, copying files with Python lets you better understand file management with Python. However, playing around with Python tasks is a way to improve your Python skill, especially if you’re a beginner.
For instance, you can change the date and time on your PC with the os module. You can even write custom bash commands with Python if you want.