How to move files in python

How to Move Files in Python: Single and Multiple File Examples

A quick way of moving a file from one place to another is using shutil.move() as shown:

We’ll look at some of the various options you’ve got for moving files around using Python. There’s also a quick example of how you could use the shutil and os libraries to tidy up your downloads folder in the first section. So if you’re someone that needs something like that in your life, then keep reading!

Option 1: shutil.move()

The example shown in the introduction uses the move() function from the shutil library. This function does what you’d expect and moves files from one location to the other, as follows:

shutil.move() works by first creating a copy of the file with the path defined by old_path and storing the copy in the new location, new_path . Finally, after the successful creation of the copy, Python deletes the original file located at old_path .

In cases where the original file is protected, shutil.move() will create a copy of the file in the new location, but Python will be unable to delete the original.

Читайте также:  Сколько html тегов существует

Most people have got quite messy download folders. So let’s look at a practical example of how we could use shutil.move() to store all the images in a download folder in a new folder called downloaded images :

Running this script inside a downloads folder will move any files with the extension .jpg or .JPG in the folder to the downloaded_images folder. Using os.listdir() returns a list of all the files in the folder. By then using os.mkdir(‘downloaded_images’) the downloaded_images folder is created. Using shutil.move() , Python can then move all the files in our images list to the new folder. This process is shown in the diagram below:

There’s a lot of room for improvement here. For example, we could upgrade our list comprehension to include more image types. We should also code in an if-else branch to see if the downloaded_images folder exists before running os.mkdir() . There’s also no reason we couldn’t expand this script to create separate folders for PDFs, executable files and anything else sitting in your downloads folder gathering dust!

Option 2: os.rename()

The os library also has a couple of options for moving files, one of these is os.rename() . os.rename() functions a little differently to shutil.move() .

Instead of copying the file in question, rename() alters the path of a file, which automatically changes the file location. See below for an example of how we could apply the function:

os.replace() works too. Despite the function being called replace() , it also moves files by renaming them. os.replace() can be implemented with an identical template to shutil.move() and os.rename() :

os.replace() and os.rename() can both be used to change a file or directory name. os.rename() reports errors differently depending on what operating system you’re running.

Whereas os.replace() will report errors uniformly across different systems, which may be the better choice when working on a program that needs compatibility with different operating systems.

Option 3: pathlib.Path().rename()

For a more object-oriented approach to moving files, pathlib is also an option.

By using the Path() function, Python creates a Path object. The rename() method then changes the path of the object, similarly to how os.rename() works:

We could also apply pathlib.Path().rename() to our script created earlier for moving images out of our downloads folder. See below for an example of this:

Below is a table that compares the speed difference of the three approaches:

Источник

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.

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()

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

Источник

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