简体   繁体   中英

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

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM