特定文件扩展名移动错误

时间:2016-11-14 11:36:19

标签: python

我编写了一个小脚本,目的是搜索任何特定文件扩展名的整个C:\并将其复制到您选择的文件夹中:

import os
import shutil


def move_all_ext(extension, source_root, dest_dir):
    # Recursively walk source_root
    for (dirpath, dirnames, filenames) in os.walk(source_root):
        # Loop through the files in current dirpath
        for filename in filenames:
            # Check file extension
            if os.path.splitext(filename)[-1] == extension:
                print("copying file: %s" % filename)
                # Move file
                shutil.copy(os.path.join(dirpath, filename), os.path.join(dest_dir, filename))



print('Welcome to the file find/copy module\n')
print('You will be asked to enter a directory name and the file type that you want to copy\n')
# Prompt new folder name
print('Enter new directory name:')
newDir = input()
print('Enter the file extension (.pdf, .txt, etc..)')
fileExt = input()

# File directory path
os.makedirs(os.path.join('C:\\Users\\Nick\\Documents\\', newDir))

# Move all specific files from C:\ to C:\Users\Nick\Documents\
move_all_ext('.' + fileExt, "C:\\", os.path.join('C:\\Users\\Nick\\Documents\\', newDir))

在运行脚本时,我有一些我不完全理解的错误:

Traceback (most recent call last):   File
"C:\Users\Nick\Documents\programming\Python\ext_copy_dest.py", line
36, in <module>
     move_all_ext('.' + fileExt, "C:\\", os.path.join('C:\\Users\\Nick\\Documents\\', newDir))   File
 "C:\Users\Nick\Documents\programming\Python\ext_copy_dest.py", line
 20, in move_all_ext
     shutil.copy(os.path.join(dirpath, filename), os.path.join(dest_dir, filename))   File
 "C:\Users\Nick\AppData\Local\Programs\Python\Python35-32\lib\shutil.py",
 line 235, in copy
     copyfile(src, dst, follow_symlinks=follow_symlinks)   File "C:\Users\Nick\AppData\Local\Programs\Python\Python35-32\lib\shutil.py",
 line 115, in copyfile
     with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nick\\Documents\\PDF\\README.txt'

我假设它有一个符号链接的问题,有没有办法编写一个IF语句来忽略任何“Permission denied”问题?

1 个答案:

答案 0 :(得分:0)

Evert指出了一个尝试 - 除了是绕过例外的最佳选择:

    if os.path.splitext(filename)[-1] == extension:
        try:
            print("copying file: %s" % filename)
            # Move file
            shutil.copy(os.path.join(dirpath, filename), os.path.join(dest_dir, filename))
        except PermissionError:
            print('Could not copy file: %s' % filename)
        except shutil.SameFileError:
            print('Could not copy duplicate file: %s' % filename)