Copy files using python

Python Copy File – Copying Files to Another Directory

Dionysia Lemonaki

Dionysia Lemonaki

Python Copy File – Copying Files to Another Directory

When working with Python, there may be times when you need to copy a file. Copying files comes in handy when you need to create a backup.

In this article, you will learn how to copy a file in Python using the shutil module and its different methods.

The shutil (short for shell utility) module in Python lets you manipulate files and directories and perform file and directory operations.

How To Copy A File Using The shutil.copyfile() Method In Python

To copy the contents of a file into another file, use the shutil.copyfile() method.

Let’s look at the following example:

# import module import shutil # copy the contents of the demo.py file to a new file called demo1.py shutil.copyfile('./demo.py', './demo1.py') 

I first import the module with the import shutil statement.

Then, I use the shutil.copyfile() method which has the following syntax:

shutil.copyfile('source_file', 'destination_file') 
  • source_file is the path to the file I want to copy – in this case, the file is the demo.py file in my current working directory ( ./ ).
  • destination_file is the path to the new file I want to create. In this case, I want to copy the contents of the source file into a new file, demo1.py , in my current working directory. The destination cannot be a directory – it must be a file name.

When I run the code from the example above, a new file named demo1.py gets created in my current working directory with a copy of demo.py ‘s contents. If the destination file already exists, it gets replaced.

Note that the shutil.copyfile() method only copies the contents of the source file.

No file metadata (such as creation dates and modification times) or file permissions are copied over to the specified destination file.

So, the shutil.copyfile() method is useful when you want to rename the file you are copying and are not concerned about saving file permissions and metadata.

How To Copy A File Using shutil.copy() Method In Python

To copy a file to another directory, use the shutil.copy() method.

Let’s look at the following example:

# import the module import shutil # Specify the path of the file you want to copy file_to_copy = './demo.py' # Specify the path of the destination directory you want to copy to destination_directory = './projects' # Use the shutil.copy() method to copy the file to the destination directory shutil.copy(file_to_copy, destination_directory) 

I first import the module using the import shutil statement.

Читайте также:  Html textarea content type

Then, I specify the path of the file I want to copy and save it in a variable named file_to_copy . In this case, I want to copy the demo.py file in my current working directory.

Next, I specify the directory I want to copy the file and save it in a variable named destination_directory . In this case, I want to save the file in the projects directory in my current working directory.

Lastly, I use the shutil.copy() method which takes two arguments:

  • The path of the file you want to copy – in this case, the variable file_to_copy .
  • The file or directory you want to copy the file into – in this case, the variable destination_directory .

When I run the code from the example above, the shutil.copy() method creates a copy of the demo.py file in the projects directory.

Keep in mind that if a file with the same name already exists in the destination directory, the existing file gets overwritten by the new file.

Another thing to keep in mind is that the shutil.copy() method copies file permissions, but it doesn’t copy metadata over to the destination directory.

How To Copy A File Using The shutil.copy2() Method In Python

The shutil.copy2() method works similarly to the shutil.copy() method.

The only difference between shutil.copy() and shutil.copy2() method is that shutil.copy2() preserves the original file metadata when copying.

# import the module import shutil # Specify the path of the file you want to copy file_to_copy = './demo.py' # Specify the path of the destination directory you want to copy the file into destination_directory = './projects' # Use the shutil.copy2() method to copy the file to the destination directory shutil.copy2(file_to_copy, destination_directory) 

How To Copy A File Using The shutil.copyfileobj() Method In Python

To copy the contents of a file object to another specified destination file object, use the shutil.copyfileobj() method. This method takes two file objects as arguments – a source file object and a destination file object. The destination cannot be a directory.

Let’s take the following example:

# import module import shutil # you have to open the source file in binary mode with 'rb' source_file = open('demo.py', 'rb') # you have to open the destination file in binary mode with 'wb' destination_file = open('project.py', 'wb') # use the shutil.copyobj() method to copy the contents of source_file to destination_file shutil.copyfileobj(source_file, destination_file) 

In the example above, the shutil.copyobj() method copies the contents of demo.py to the project.py file.

Keep in mind that this method does not preserve file permissions and it doesn’t copy metadata.

Conclusion

And there you have it! You now know how to copy files in Python using the shutil module and the methods it offers.

To help you choose which method to use, refer to the following table that summarises what each method does.

Читайте также:  Селекторы атрибутов
Method Preserves permissions? Copies metadata? Can destination be a directory? Accepts file object?
shutil.copyfile() No No No No
shutil.copy() Yes No Yes No
shutil.copy2() Yes Yes Yes No
shutil.copyfileobj() No No No Yes

To learn more about Python, check out freeCodeCamp’s Python for beginners course.

Thanks for reading, and happy coding!

Источник

Python: Copy a File (4 Different Ways)

Python Copy a File Cover Image

In this tutorial, you’ll learn how to use Python to copy a file using the built-in shutil library. You’ll learn a total of four different ways to copy, depending on what your needs are. You’ll learn how to copy a file to a direct path, to a directory, include metadata, and copy permissions of the file.

Knowing how to copy a file is an important skill that allows you to, for example, create a backup of a file before modifying it using your script.

The Quick Answer: Use shutil

Quick Answer - Python Copy File

Overview of Shutil Copy Methods

The shutil library provides a number of different copy methods, each of which copy files, but do so slightly differently. The table below provides a helpful overview of these different copy methods, allowing you to choose the method that’s best suited for your purpose.

The sections that follow go deeper into the different methods, providing step-by-step instructions with easy to follow examples.

Function Include File Metadata Requires File Destination Copies the File Object
.copy() x x
.copyfile() x x x
.copy2() x
.copyfileobj() x x

In the next section, you’ll learn how to copy a file with Python to a particular path.

Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!

Copy a File with Python to a Particular Path

The shutil.copyfile() method copies a file to another destination file path, meaning that we need to specify not just the destination directory (folder), but also the filename and extension we want to use. This can be very helpful if you want to move and rename the file you’re copying.

Let’s take a look at how we can use the shutil.copyfile() method to copy a file using Python:

# Copy a file to a destination with shutil.copyfile() import shutil shutil.copyfile('/Users/datagy/Desktop/file.py', '/Users/datagy/Desktop/file2.py')

Some things to make note of here:

  • Both the source and destination file paths must be entire file paths, rather than just directories
  • If a file already exists in its destination, it will be replaced
  • Metadata will not be copied over

In the next section, you’ll learn how to use Python to copy a file to a particular directory using the

Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!

Copy a File with Python to a Particular Directory

If you simply want to copy a file to a destination folder without specifying a filename for it, you can use the shutil.copy() method. The method allows you to specify a destination file path or directory. This can be helpful when you simply want to copy multiple files to a given destination.

Читайте также:  Вывести массив строкой python

Let’s take a look at how we can copy a file to a directory using shutil.copy() :

# Copy a file to a destination with shutil.copy() import shutil shutil.copy('/Users/datagy/Desktop/file.py', '/Users/datagy/Desktop/Folder/')

Some additional things to make note of:

  • The source must be a complete file path, but the destination can be either a file path or a directory path
  • If a file already exists in the destination, the file will be replaced
  • No metadata is copied over

In the next section, you’ll learn how to copy a file and preserve metadata with Python.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Copy a File with Metadata in Python

By default, the above methods don’t copy the metadata of the data. This, for example, can contain the created date. If this is important, you can use the shutil.copy2() method.

Let’s see how we can do this:

# Copy a file to a destination with shutil.copy2() with metadata import shutil shutil.copy('/Users/datagy/Desktop/file.py', '/Users/datagy/Desktop/Folder/')

Let’s take a look at some additional notes on this method:

  • The source must be a full file path, but the destination can be either a file path or a directory
  • Meta data will be preserved
  • If a file already exists in the destination, it will be overwritten

In the next section, you’ll learn how to copy an entire file object using Python.

Copy a File with Python as a File Object

You can also copy a file as a file object by using the shutil.copyfileobj() method. This method, instead of taking file paths, takes file-like objects as its arguments.

Because of this, we need to first open the file to copy it successfully.

Let’s see how we can do this:

# Copy a file to a destination with shutil.copyfileobj() import shutil source_file_path = '/Users/nikpi/Desktop/file.py' source_file = open(source_file_path, 'rb') destination_file_path = '/Users/nikpi/Desktop/file.py' destination_file = open(source_file_path, 'wb') shutil.copyfileobj(source_file, destination_file)

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Conclusion

In this post, you learned four different ways to copy a file in Python using the shutil library. Knowing the advantages and implications of the different approaches can make you get the results you really wanted. Copying files programatically can be an incredibly helpful skill to leverage the advantages of programming, especially when you’re dealing with hundreds of files.

To learn more about the shutil library, check out the official documentation here.

Источник

Оцените статью