How Python Copy a File – 9 Simple & Quick Ways

1. How Python Copy a File?

In our last tutorial, we studied Python Zipfile. Today, in this Python Tutorial, we will discuss how python copy a file. Moreover, we will look at the 9 simple ways to copy a file in Python Programming: Using Python OS Module, Python Threading Library, Python Subprocess Module, Python Shutil Module.

So, let’s start How Python Copy a File.

How Python Copy a File - 9 Simple & Quick Ways

How Python Copy a File – 9 Simple & Quick Ways

Python Interview Questions

2. How Python Copy a File?

Here, are main 4 categories of ways through which Python Copy a file.

a. Using Python OS Module

There are two ways to copy a file in Python- the popen() method and the system() method. Let’s discuss them.

How Python Copy a File - 9 Simple & Quick Ways

How Python Copy a File – 9 Simple & Quick Ways

i. popen()

The popen() method returns a file object that connects to a pipe. In mode ‘w’, we can write to it, and in mode ‘r’, we can read from it (‘r’ is the default). You can say that it creates a pipe to a command or from it.
Read About Python Directory and Files Management
This is the syntax we use:

os.popen(command[, mode[, bufsize]])

Here, command is the command we use, and mode is ‘r’ or ‘w’, as discussed previously. When bufsize is 0, there is no buffering. When it is 1, there is line buffering when accessing a file. When it is an integer greater than 1, there is buffering with the indicated buffer size. For a negative value, a default buffer size is used.
We have a file labeled ‘1.txt’ on the Desktop. We use the following code:

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.popen('copy 1.txt 2.txt')

As you can see, this creates a new file labeled ‘2.txt’ on the Desktop. This has the same contents as 1.txt. For Linux, you’d have to write ‘cp’ instead of ‘copy’. This method has been deprecated in Python 2.6.

ii. system()

The system() method lets us execute a command as a string in a subshell. Any output the command generates goes to the interpreter standard output stream.
The syntax is:


Let’s try doing the same thing using system() here.

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.system('copy 1.txt 2.txt')

We can see the same action with this method. It copies the contents of a file 1.txt into a new file 2.txt.
Let’s revise Python File I/O – Python Write to File and Read File
Note that if we already had a file called 2.txt, this operation replaces its contents. This applies to the previous method as well.
While this method is similar to popen(), it executes in a subshell. It executes in a separate thread parallel to our executing code. By calling .wait() on the object it returns, we can wait for its completion.

b.  Using Python Threading Library

We can borrow the Thread module from the threading library to Python copy a file. This does the copying in an async manner.

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> import shutil
>>> from threading import Thread
>>> Thread(target=shutil.copy, args=['1.txt','2.txt']).start()

This code copies the contents of file 1.txt to a new file 2.txt. If your application uses multiple threads for reading or writing a file, you should employ locking to avoid deadlocks.

c. Using Python Subprocess Module

The subprocess module lets us work with child processes- launch them, attach to their pipes for input, output, and error, and retrieve return values. From this module, we can use the methods call() and check_output(), for Python copy a file.
Let’s see how this module helps python copy a file.

Python copy a file - Python Subprocess Module

Python Copy a File – Python Subprocess Module

i. call()

The syntax for this command is the following:, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

This method runs the command that args describes. It waits for the command to complete and then returns the attribute returncode. We use the following code to copy a file:

>>> import os, subprocess
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>>'copy 1.txt 2.txt', shell=True)
>>> if status!=0:
       if status<0:
            print(f"Killed by signal {status}")
            print(f"Command failed with return code {status}")
            print("Successfully executed command")

Successfully executed command
Let’s Discuss Python Modules in Details
Since here we get the output we do, we figure that the code returns a 0.

ii. check_output()

Now, let’s try the same with check_output(). This method runs commands with arguments and returns the output. For a non-zero return code, it raises a CalledProcessError. It also supports pipes. This is the syntax to follow:

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

This method is a lot like, but it pipes data from stdout as encoded bytes by default. Let’s see how we can copy a file with it.

>>> import os, subprocess
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> status=subprocess.check_output('copy 1.txt 2.txt',shell=True)

d. Using Python Shutil Module

There are four methods we will consider in this module to help Python copy a file- copyfile(), copy(), copy2(), and copyfileobj().
Let’s Read the List of 63 Python os Modules in 2018

Python copy a file - Python shutil Modules

Python copy a file – Python shutil Modules

i. copyfile()

copyfile() copies one file’s contents into another. For this, the target should be writable; otherwise, it raises an IOError. When the destination is a directory, it raises Error 13. And like we discussed previously, these methods replace a destination file if it already exists and throw an error if the source and destination names are the same.

We have the following syntax for it:

shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

Let’s try the following code:

>>> import os,shutil
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> shutil.copyfile('1.txt','2.txt')

This code gives us the name of the file it created. Also, when we set the follow_symlinks argument to False, it creates a symbolic link from the source file, which is a symbolic link, instead of copying it.

ii. copy()

Like copyfile(), copy() lets us copy content from one file to another. However, this one also copies file system permissions.
Do you know about Errors and Exceptions in Python Programming

We have the following syntax:

shutil.copy(src_file, dest_file, *, follow_symlinks=True)

Let’s try copying with this method too:

>>> import os,shutil
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> shutil.copy('1.txt','2.txt')

So then, what is different here from copyfile()? Here we go:

  1. copyfile() copies data, copy() also copies permission bits
  2. copy() can copy to directories, copyfile() raises an Error 13 instead
  3. copyfile() uses method copyfileobj() in its implementation, but copy uses functions copyfile() and copymode() in turn
  4. The last aspect makes copy() slower than copyfile(), which doesn’t have the overhead of preserving permissions

iii. copy2()

This one’s like copy(), but while copying the data, it also gets access and modification times linked to the metadata. For platforms that do not allow for full metadata saving, it preserves any metadata it can.

We have the following syntax:

shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

Now let’s hit the payload.

>>> import os,shutil
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> shutil.copy2('1.txt','2.txt')

This method preserves the creation date. Let’s see the differences between copy() and copy2().

  1. copy() sets permission bits, copy2() also updates file metadata with timestamps
  2. Internally, copy() calls copyfile() and copymode(); copy2() calls copyfile() and copystat()

Let’s Explore the Difference Between Python Modules vs Packages

iv. copyfileobj()

If you have been reading from your source file object, copyfileobj() will start copying from the position you stopped reading at.

It has the following syntax:

shutil.copyfileobj(src_file_object, dest_file_object[, length])

Here, source and destination file parameters refer to objects. length is the buffer size. This is the number of bytes in memory during a copy. This comes in handy when copying very large files, and the default is 16KB. Let’s copy using this last method.

>>> import os,shutil
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> one=open('1.txt','rb')
>>> two=open('2.txt','wb')
>>> shutil.copyfileobj(one,two)

Remember to open the files in binary mode. Open the source file as readable and the destination file as writable. Also, remember to close the files once you’re done.
So, this was all about How Python Copy a File. Hope you like our explanation.

3. Conclusion

Hence, in this tutorial, we discussed nine ways for Python copy a file. Moreover, we discussed the commands in the Python OS Module, Python Threading Library, Python Subprocess Module, and Python Shutil Module. Which one do you prefer? Comment below.
Related Topic-

Python Deep Copy
For reference

Leave a Reply

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