Moving multiple file types (*.jpg, *.pdf and *.tiff) to another directory with Python

时间:2019-04-16 23:23:18

标签: python python-3.x

I'd like to move files with selected formats/types (eg: pdf, jpg and tiff) to another directory.

Currently, I have this code below that moves ALL files from dir1 and its sub-directories to dir2:

for root, dirs, files in os.walk(dir1, topdown=True):
    for name in files:
        shutil.move(os.path.join(root, name), os.path.join(dir2, name))

But the above codes include all files.

I just want to move the pdf, tiff and jpg files, and leave all other file formats behind in the original directory. Can anyone help?

3 个答案:

答案 0 :(得分:1)

Split the filename on '.' and take the last part, keep a list of file extensions you would like to copy, and check if it's in the list.

file_extensions = ['jpg', 'pdf', 'tiff']
for root, dirs, files in os.walk(dir1, topdown=True):
    for name in files:
        if name.split('.')[-1] in file_extensions:
            shutil.move(os.path.join(root, name), os.path.join(dir2, name))

答案 1 :(得分:0)

Something like this would be the straightforward approach:

for root, dirs, files in os.walk(dir1, topdown=True):
    for name in files:
        if name.endswith(".pdf") or name.endswith(".jpg") or name.endswith(".tiff"): 
            shutil.move(os.path.join(root, name), os.path.join(dir2, name))

答案 2 :(得分:0)

Try glob

for root, dirs, files in os.walk(dir1, topdown=True):
    files_ok = glob.glob(root + '/*.pdf')
    files_ok += glob.glob(root + '/*.tiff')
    files_ok += glob.glob(root + '/*.jpg')
    for name in files_ok:
        shutil.move(os.path.join(root, name), os.path.join(dir2, name))