tags:

views:

164

answers:

4

How to copy all the files in one directory to another in python. I have the source path and the destination path in a string.

A: 

See the shutil.copytree function.

jchl
But i dont want to copy the subdirs in this directory
hidayat
A: 

Look at shutil. http://docs.python.org/library/shutil.html

specifically the copytree command.

Doon
A: 

If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*") to get a list of all the filenames, loop over the list and use shutil.copy to copy each file.

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)
Steven
Note: You might have to check the glob results with os.path.isfile() to be sure they are filenames. See also GreenMatt's answer. While glob does return only the filename like os.listdir, it still returns directory names as well. The '*.*' pattern might be enough, as long as you don't have extensionless filenames, or dots in directory names.
Steven
A: 

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