Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy multiple files in Python

Tags:

python

file

copy

How to copy all the files present in one directory to another directory using Python. I have the source path and the destination path as string.

like image 744
hidayat Avatar asked Aug 03 '10 14:08

hidayat


People also ask

How do I copy all files in a directory in Python?

The shutil. copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another. The destination should not be an existing directory.

How do I copy a group of files?

Step 1: Click on the first file to be selected. Step 2: Hold down Ctrl and click on all the files that you want to select additionally. Step 2: Press the Shift key and click on the last file. Step 3: You have now selected all files at once and can copy and move them.


1 Answers

You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.

The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).

import os import shutil src_files = os.listdir(src) for file_name in src_files:     full_file_name = os.path.join(src, file_name)     if os.path.isfile(full_file_name):         shutil.copy(full_file_name, dest) 
like image 168
GreenMatt Avatar answered Sep 22 '22 07:09

GreenMatt