Python os copy file to folder

How to Copy File and Rename in Python?

In this Python tutorial, I have explained, how to copy file and rename in Python.

Copy File and Rename in Python

Python provides various ways to copy and rename files:

  1. Using the shutil library for copying files.
  2. Using the os library for renaming and handling file paths.

Using the shutil Library to Copy Files

The shutil (shell utility) module in Python provides functions to operate on files and collections of files. It comes in handy when you want to copy files.

Here’s how you can use the shutil library to copy a file:

Example 1: Basic File Copy

import shutil # Specify the source file and the destination (including the new file name) source_file = 'path/to/your/source/file.txt' destination_file = 'path/to/your/destination/new_file.txt' # Copy the file shutil.copy2(source_file, destination_file)

In this example, shutil.copy2 is used to copy the file from the source to the destination. It also preserves the file’s metadata.

Using the os Library to Rename Files

While shutil can be used for copying, the os module is useful for renaming files, and also for handling file paths.

Here’s how you can use the os library to rename a file:

Example 2: Basic File Rename

import os # Specify the current file name and the new file name current_file = 'path/to/your/current/file.txt' new_file = 'path/to/your/new/file.txt' # Rename the file os.rename(current_file, new_file)

Here is the complete code:

import shutil import os # Specify the source file, the destination for the copy, and the new name source_file = 'path/to/your/source/file.txt' destination_directory = 'path/to/your/destination/' new_file_name = 'new_file.txt' # Copy the file shutil.copy2(source_file, destination_directory) # Get the base name of the source file base_name = os.path.basename(source_file) # Construct the paths to the copied file and the new file name copied_file = os.path.join(destination_directory, base_name) new_file = os.path.join(destination_directory, new_file_name) # Rename the file os.rename(copied_file, new_file)

Python copy file and rename

Here, we can see how to copy file and rename in Python.

  • In this example, I have imported Python modules called shutil and os.
  • Firstly, we have to copy the file from source to destination and then rename the copied file.
  • src = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt’ is the source path. name.txt is the file name that I have created with the .txt extension.
  • dst = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\name.txt’ is the destination path. The name.txt is the file name that I have created with the .txt extension.
  • os.rename is used to rename the folder name. To rename the file, I have used os.rename(r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt’,r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\details.txt’)
  • shutil.copyfile(src, dst) is used to copy the file from source to destination.
  • The name.txt file name is now renamed by the name called details.txt.
import shutil import os src = r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt' dst = r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\name.txt' shutil.copyfile(src, dst) os.rename(r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt',r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\details.txt' )

The above code, we can use to copy file and rename in Python.

Читайте также:  Php проверка даты регулярным выражением

You may like the following Python tutorials:

In this Python tutorial, I have explained, how to copy and rename file in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

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.
Читайте также:  Php просмотр циклом массива

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.

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.

Читайте также:  Операции с коллекциями python

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!

Источник

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