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.
But i dont want to copy the subdirs in this directory
hidayat
2010-08-03 14:57:01
A:
Look at shutil. http://docs.python.org/library/shutil.html
specifically the copytree command.
Doon
2010-08-03 14:57:22
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
2010-08-03 15:56:32
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
2010-08-04 08:22:01
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
2010-08-03 17:59:51