How to Move Files and Directories in Python?


In this post, we’ll learn how to move files and directories in Python. We’ll also touch on some of the quirks of working with files and directories in Python. By the end of this post, you’ll be able to move files and directories around like a pro!

Moving Files with the shutil Module

The shutil module provides a functions for copying files, as well as entire directories. To use the shutil functions, you first need to import the module:

import shutil
Code language: JavaScript (javascript)

Now that we’ve imported the shutil module, let’s start by looking at how to move a file with shutil. Moving a single file is pretty straightforward:

shutil.move("/path/to/source/file.txt", "/path/to/destination/file.txt")
Code language: JavaScript (javascript)

This will move the file “file.txt” from “/path/to/source” to “/path/to/destination”. If “/path/to/destination” does not exist, then it will be created for you.

Example 1:

import shutil # absolute path path_source = r"E:\mydata\flowers\flower_orchid.jpg" path_destination = r"E:\\Orchid\flower_orchid.jpg" shutil.move(path_source, path_destination)
Code language: Python (python)

Example 2:

Let’s say you want to move a file, but it already has the same name in the new location. In this case, you can move the file by giving it a new name.

import os import shutil path_source = r"D:\source_dir\flowers\\" path_destination = r"D:\\destination_dir\flowers\\" file_name = 'flower_orchid.jpg' # check if file exist in destination folder if os.path.exists(path_destination + file_name): # Split name and extension data = os.path.splitext(file_name) only_name = data[0] extension = data[1] # Adding the new name new_file = only_name + '_new' + extension # construct full path for new file path_new_file = os.path.join(path_destination, new_file) # move file shutil.move(path_source + file_name, path_new_file) else: shutil.move(path_source + file_name, path_destination + file_name)
Code language: Python (python)

Example 3: Move all files from the source folder into the destination folder.

Use the os.listdir() function to get a list of all the files in the source folder. It gives back a list of all the file and folder names in the given directory.

import os import shutil src_folder = r"D:\source\\" dest_folder = r"D:\destination\\" # Get all files for file_name in os.listdir(src_folder): # construct full file path source = src_folder + file_name destination = dest_folder + file_name # move only files if os.path.isfile(source): shutil.move(source, destination) print('Moved:', file_name)
Code language: Python (python)

Example 4: Move files based on file extension

In this example, we will use glob and shutil module to move files that have a .jpg extension.

move files with jpg extension
import glob import os import shutil src_folder = r"D:\source\\" dst_folder = r"D:\destination\\" # Search files with .jpg extension in source directory pattern = "\*.jpg" files = glob.glob(src_folder + pattern) # move the files with .jpg 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)
Code language: Python (python)

The glob.glob() method returns a list of files or folders that match the pattern given in the pathname argument.

Let’s take the following file/directory structure as an example.

data/ ├── 012.txt ├── abc.txt ├── dir │ ├── 789.txt │ └── xyz.text └── file.text

Script 1

import glob print(glob.glob('data/*.txt')) # ['temp/abc.txt', 'data/012.txt']
Code language: PHP (php)

Script 2:

print(glob.glob('data/**', recursive=True)) # ['data/', 'data/file.text', 'data/abc.txt', 'data/012.txt', 'data/dir', 'data/dir/xyz.text', 'data/dir/789.txt']
Code language: PHP (php)

Script 3:

print(glob.glob('data/**/*.txt', recursive=True)) # ['data/abc.txt', 'data/012.txt', 'data/dir/789.txt'] print(glob.glob('data/**/*.text', recursive=True)) # ['data/file.text', 'data/dir/xyz.text']
Code language: PHP (php)

Script 4:

print(glob.glob('data/**/???.text', recursive=True)) # ['data/dir/xyz.text'] print(glob.glob('data/**/[0-9][0-9][0-9].txt', recursive=True)) # ['data/012.txt', 'data/dir/789.txt']
Code language: PHP (php)

Script 5:

import glob import re print(glob.glob('data/**', recursive=True)) # ['data/', 'data/file.text', 'data/abc.txt', 'data/012.txt', 'data/dir', 'data/dir/xyz.text', 'data/dir/789.txt'] print([p for p in glob.glob('data/**', recursive=True) if re.search('\d+\.txt', p)]) # ['data/012.txt', 'data/dir/789.txt'] print([p for p in glob.glob('data/**', recursive=True) if re.search('/\D{3}\.(txt|text)', p)]) # ['data/abc.txt', 'data/dir/xyz.text']
Code language: PHP (php)

Script 6: By defining a function like the one below, you can move multiple files at once, using glob.glob()

import shutil import glob import os def move_glob(dst_path, pathname, recursive=True): for p in glob.glob(pathname, recursive=recursive): shutil.move(p, dst_path)
Code language: Python (python)

Example 5: Move Files based on the filename

import glob import os import shutil src_folder = r"E:\source\\" dst_folder = r"E:\destination\\" # move file whose name starts with string 'flower' pattern = src_folder + "\flower*" 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('File Moved:', file)
Code language: Python (python)

Move Directories in Python

You can also move an entire directory with the shutil.move() function

The syntax is similar to moving a single file, but with one key difference. When moving a directory, you need to specify the destination directory name as the last argument:

shutil.move("/path/to/source/folder", "/path/to/destination")
Code language: JavaScript (javascript)

This will rename “/path/to_source_folder” to “/path/to_destination”.

Example 1: Move a folder with multiple files

import shutil from os import path # Set the directory path of the files to move source_path = "/user/david/folder_source/images" # Check the directory path exist or not if path.exists(source_path): # Set the destination directory path destination_path = "/user/david/folder_destination/images" # Move the directory with files to the new location new_location = shutil.move(source_path, destination_path) # Print the new location print("The {0} is moved to the location,{1}".format(source_path, new_location)) else: # Print the message if the directory path not exists print("Invalid directory location.")
Code language: Python (python)

Example 2: Move a folder with multiple files and directories

import os # Set the directory path of the files to move source_path = "/users/david/my_docs/" # Check the directory path exist or not if os.path.exists(source_path): # Set the destination directory path destination_path = "/users/david/files/" # Get a list of files and folders of the source path file_list = os.listdir(source_path) # Iterate the files and folders list for file_name in file_list: os.rename(source_path + file_name, destination_path + file_name) # Print the new location print("All files and folders of {0} is moved to the location, {1}".format(source_path, destination_path)) else: # Print the message if the directory path not exists print("Invalid directory path.")
Code language: Python (python)

The shutil module provides everything you need for moving files and directories around in Python. You can use the shutil.move() function to move a file or directory from one location to another. J

ust keep in mind that when you’re moving directories, you need to specify the destination directory name as the last argument. With that knowledge in hand, you’re ready to start moving files like a pro!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts