2016-11-14 140 views
0

我寫了一個小腳本搜索整個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語句忽略任何「權限被拒絕」問題的方法嗎?

+0

使用'嘗試 - 除了PermissionError'代替if語句。 – Evert

+0

我覺得沒有搞清楚,謝謝你的工作 – chilledheat

回答

0

埃弗特指出,一試 - 除了是讓周圍的例外是最好的選擇:

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)