特定文件扩展名移动

2024-04-25 00:39:20 发布

您现在位置: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语句来忽略任何“权限被拒绝”的问题


Tags: pathinosallfilenameusersextnick
1条回答
网友
1楼 · 发布于 2024-04-25 00:39:20

埃弗特指出,尝试例外是绕过例外的最佳选择:

    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)

相关问题 更多 >