特定文件扩展名动错误
问题描述:
我写了一个小脚本搜索整个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语句忽略任何“权限被拒绝”问题的方法吗?
答
埃弗特指出,一试 - 除了是让周围的例外是最好的选择:
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)
使用'尝试 - 除了PermissionError'代替if语句。 – Evert
我觉得没有搞清楚,谢谢你的工作 – chilledheat