Python copy all files one directory another

Move Files Or Directories in Python

In this Python tutorial, you’ll learn how to move files and folders from one location to another.

After reading this article, you’ll learn: –

  • How to move single and multiple files using the shutil.move() method
  • Move files that match a pattern (wildcard)
  • Move an entire directory

Steps to Move a File in Python

Python shutil module offers several functions to perform high-level operations on files and collections of files. We can move files using the shutil.move() method. The below steps show how to move a file from one directory to another.

  1. Find the path of a file We can move a file using both relative path and absolute path. The path is the location of the file on the disk.
    An absolute path contains the complete directory list required to locate the file. For example, /home/Pynative/s ales .txt is an absolute path to discover the sales.txt.
  2. Use the shutil.move() function The shutil.move() function is used to move a file from one directory to another.
    First, import the shutil module and Pass a source file path and destination directory path to the move(src, dst) function.
  3. Use the os.listdir() and shutil move() function to move all files Suppose you want to move all/multiple files from one directory to another, then use the os.listdir() function to list all files of a source folder, then iterate a list using a for loop and move each file using the move() function.

Example: Move a Single File

Use the shutil.move() method move a file permanently from one folder to another.

shutil.move(source, destination, copy_function = copy2)
  • source : The path of the source file which needs to be moved.
  • destination : The path of the destination directory.
  • copy_function : Moving a file is nothing but copying a file to a new location and deletes the same file from the source. This parameter is the function used for copying a file and its default value is shutil.copy2() . This could be any other function like copy() or copyfile() .

In this example, we are moving the sales.txt file from the report folder to the account folder.

import shutil # absolute path src_path = r"E:\pynative\reports\sales.txt" dst_path = r"E:\pynative\account\sales.txt" shutil.move(src_path, dst_path)
  • The move() function returns the path of the file you have moved.
  • If your destination path matches another file, the existing file will be overwritten.
  • It will create a new directory if a specified destination path doesn’t exist while moving file.

Move File and Rename

Let’s assume your want to move a file, but the same file name already exists in the destination path. In such cases, you can transfer the file by renaming it.

Читайте также:  Php file folder listing

Let’s see how to move a file and change its name.

  • Store source and destination directory path into two separate variables
  • Store file name into another variable
  • Check if the file exists in the destination folder
  • If yes, Construct a new name for a file and then pass that name to the shutil.move() method.

Suppose we want to move sales.csv into a folder called to account, and if it exists, rename it to sales_new.csv and move it.

import os import shutil src_folder = r"E:\pynative\reports\\" dst_folder = r"E:\pynative\account\\" file_name = 'sales.csv' # check if file exist in destination if os.path.exists(dst_folder + file_name): # Split name and extension data = os.path.splitext(file_name) only_name = data[0] extension = data[1] # Adding the new name new_base = only_name + '_new' + extension # construct full file path new_name = os.path.join(dst_folder, new_base) # move file shutil.move(src_folder + file_name, new_name) else: shutil.move(src_folder + file_name, dst_folder + file_name)

Move All Files From A Directory

Sometimes we want to move all files from one directory to another. Follow the below steps to move all files from a directory.

  • Get the list of all files present in the source folder using the os.listdir() function. It returns a list containing the names of the files and folders in the given directory.
  • Iterate over the list using a for loop to get the individual filenames
  • In each iteration, concatenate the current file name with the source folder path
  • Now use the shutil.move() method to move the current file to the destination folder path.

Example: Move all files from the report folder into a account folder.

import os import shutil source_folder = r"E:\pynative\reports\\" destination_folder = r"E:\pynative\account\\" # fetch all files for file_name in os.listdir(source_folder): # construct full file path source = source_folder + file_name destination = destination_folder + file_name # move only files if os.path.isfile(source): shutil.move(source, destination) print('Moved:', file_name)

Our code moved two files. Here is a list of the files in the destination directory:

Use the os.listdir(dst_folder) function to list all files present in the destination directory to verify the result.

Move Multiple Files

Let’s assume you want to move only a few files. In this example, we will see how to move files present in a list from a specific folder into a destination folder.

import shutil source_folder = r"E:\pynative\reports\\" destination_folder = r"E:\pynative\account\\" files_to_move = ['profit.csv', 'revenue.csv'] # iterate files for file in files_to_move: # construct full file path source = source_folder + file destination = destination_folder + file # move file shutil.move(source, destination) print('Moved:', file)
Moved: profit.csv Moved: revenue.csv

Move Files Matching a Pattern (Wildcard)

Suppose, you want to move files if a name contains a specific string.

The Python glob module, part of the Python Standard Library, is used to find the files and folders whose names follow a specific pattern.

glob.glob(pathname, *, recursive=False)
  • We can use the wildcard characters for pattern matching. The glob.glob() method returns a list of files or folders that matches the pattern specified in the pathname argument.
  • Next, use the loop to move each file using the shutil.move()
Читайте также:  Create Record

Refer to this to use the different wildcards to construct different patterns.

Move files based on file extension

In this example, we will move files that have a txt extension.

import glob import os import shutil src_folder = r"E:\pynative\report" dst_folder = r"E:\pynative\account\\" # Search files with .txt extension in source directory pattern = "\*.txt" files = glob.glob(src_folder + pattern) # move the files with txt extension for file in files: # extract file name form file path file_name = os.path.basename(file) shutil.move(file, dst_folder + file_name) print('Moved:', file)
Moved: E:\pynative\report\revenue.txt Moved: E:\pynative\report\sales.txt

Move Files based on filename

Let’s see how to move a file whose name starts with a specific string.

import glob import os import shutil src_folder = r"E:\pynative\reports" dst_folder = r"E:\pynative\account\\" # move file whose name starts with string 'emp' pattern = src_folder + "\emp*" for file in glob.iglob(pattern, recursive=True): # extract file name form file path file_name = os.path.basename(file) shutil.move(file, dst_folder + file_name) print('Moved:', file)
Moved: E:\pynative\reports\emp.txt

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

How to copy files from one folder to another using Python?

A file is a collection of information or data that is stored on a computer. You are already familiar with several file types, such as your audio, video, and text files.

Text files and binary files are the two categories into which we often split files. Simple text is contained in text files, as opposed to binary data, which can only be read by computers.

A group of files and subdirectories is called a directory or folder. A subdirectory is a directory present inside a directory. Numerous operating system functions can be carried out automatically.

File Operations Using Python

Python provides various methods to perform operations on the files and folders of the underlying operating system.

  • The OS module in Python has functions for adding and deleting folders, retrieving their contents, changing the directory, locating the current directory, and more. Import this module, we will use the listdir() method of it to fetch the files.
  • Similarly, the shutil module provides a number of functions for dealing with operations on files and associated collections. It gives users the option to copy and delete files. You can copy the contents of one folder to another using the shutil.copy(), shutil.copy2() and shutil.copytree() methods of this module.

You can include these functions in your file by importing their respective modules as shown below −

import shutil shutil.submodule_name(arguments passed)

Using shutil.copy() operation

Using this function, the text or content of the source file is copied to the target file or directories. Additionally, the permission mode of the file is preserved, but the file metadata (such as the “Date Creation”, “Date Modification” etc..) is not preserved.

Читайте также:  Css peek vs code

Syntax

Following is the syntax of the shutil.copy() method−

  • Origin − A string containing the source file’s location or path
  • Target − A string containing the destination file’s location or path.

Example

Following is an example of to copy files from one folder to other using shutil.copy() operation −

# importing the modules import os import shutil # Providing the folder path origin = 'C:\Users\Lenovo\Downloads\Works\' target = 'C:\Users\Lenovo\Downloads\Work TP\' # Fetching the list of all the files files = os.listdir(origin) # Fetching all the files to directory for file_name in files: shutil.copy(origin+file_name, target+file_name) print("Files are copied successfully")

Output

Following is an output of the above query:

Files are copied successfully

Note − Both a relative and an absolute path can be used to copy a file. The file’s location on the disc is indicated by the path

The whole directory list needed to find the file is contained in an absolute path. For instance, an absolute path to find samples.txt is− C:\Users\Lenovo\Downloads\Works.

Here we are providing the folder path of both the source and the destination of the files.

Using shutil.copy2() operation

First of all, this function is exactly like copy() with the exception that it keeps track of the source file’s metadata.

The execution program for this is exact same as shutil.copy(). The only difference is that while fetching the file to directory, in place of shutil.copy() we write shutil.copy2().

shutil.copy2(origin+file_name, target+file_name)

Syntax

Following is the syntax of the shutil.copy2() method –

Origin and target values are same as defined above.

The copy2() function in this code does one additional operation in addition to a copy() which is to keep the metadata.

Using shutil.copytree() method

This function moves a file and any subdirectories it contains from one directory to another.

This indicates that both the source and the destination include the file. The string must contain the names of both parameters.

Syntax

Following is the syntax of the shutil.copytree() method –

shutil.copytree(origin, target)

Origin and target values are same as defined above.

Example

Following is an example of to copy files from one folder to other using shutil.copytree() operation:

# importing the module import shutil # Fetching all the files to directory shutil.copytree('C:\Users\Lenovo\Downloads\Works\','C:\Users\Lenovo\Downloads\Work TP\/newfolder') print("File Copied Successfully")

Output

Following is an output of the above query:

As an output we will be able to see the changes made after the execution i.e. the ‘Works’ folder gets copied to the ‘Works TP’ folder with the name of ‘newfolder’ as assigned in the code above containing all the files inside it which was there in the Works folder.

In order to obtain a duplicate of that file, we have included the copytree() function in this code.

Источник

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