Skip to content

Instantly share code, notes, and snippets.

@chaomai
Created September 8, 2012 09:19
Show Gist options
  • Save chaomai/3672983 to your computer and use it in GitHub Desktop.
Save chaomai/3672983 to your computer and use it in GitHub Desktop.
Python 3: copy to target location 2
#scan a directory iteratively, copy particular file to a new directory
#each file in new directory has is own new directory that name is same as the file
#tested under Python3
import os
import os.path
import shutil
def copy_file(item, sou_dir, des_dir, type):
(filepath, filename) = os.path.split(item)
if type == os.path.splitext(filename)[1]:
sourcefile = os.path.join(sou_dir, item)
if not os.path.exists(des_dir):
os.makedirs(des_dir)
targetfile = os.path.join(des_dir, os.path.splitext(filename)[0])
os.makedirs(targetfile)
targetfile = os.path.join(targetfile, filename)
shutil.copyfile(sourcefile, targetfile)
print('Success: ' + sourcefile + ' to ' + targetfile)
else:
return
def find_and_operate(sou_dir, des_dir, type):
for item in os.listdir(sou_dir):
subdir = os.path.join(sou_dir, item)
if os.path.isfile(subdir):
copy_file(item, sou_dir, des_dir, type)
else:
find_and_operate(subdir, des_dir, type)
if __name__ == '__main__':
source = input('source directory:')
destination = input('destination directory:')
type = input('filetype:')
find_and_operate(source, destination, type)
print('Done')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment