为什么我不能使用shutil复制.CR2文件?

时间:2017-02-27 00:38:28

标签: python shutil

import os
import shutil
os.chdir('C:\\')

dir_src = ('C:\\Users\\Tibi\\Desktop\\New Folder\\New Folder')
dir_dst = ('D:\\test')


for folder in os.walk(dir_src):
    print(folder)
    for filename in os.listdir(dir_src):
        if filename.endswith('.CR2'):
            shutil.copy(dir_src + filename, dir_dst)
        print(filename)

请注意,导致其退出的文件是我要复制到测试文件夹的文件之一。我尝试使用其他文件类型,但它们也不起作用。

输出:

Traceback (most recent call last):
  File "copyfiletree.py", line 14, in <module>
    shutil.copy(dir_src + filename, dir_dst)
  File "C:\Users\Tibi\Anaconda3\lib\shutil.py", line 235, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Users\Tibi\Anaconda3\lib\shutil.py", line 114, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\New FolderIMG_5221.CR2'

我想我应该提到我的计算机感染了Spora勒索软件(但是,这些文件没有加密)。

新代码我正在尝试使用:

import os
import shutil
#os.chdir('C:\\')

dir_src = ('D:\\Users\\Tibi\\Pictures')
dir_dst = ('D:\\test')

#while True:
#    try:
#        for folder in os.walk(dir_src):
#            print(folder)
#            for filename in os.listdir(dir_src):
#                if filename.endswith('.CR2'):
#                    shutil.copy(dir_src + '\\' + filename, dir_dst)
#                print(filename)
#    except UnicodeEncodeError:
#        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>File %s was Skipped!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" %filename)
import pathlib
import glob

dir_src = pathlib.Path(r'D:\\Users\\Tibi\\Pictures//Move')
dir_dst = pathlib.Path(r'D:\test')

for file in dir_src.rglob('*.mp4'):
    shutil.copy(str(file), str(dir_dst / file.name))
    print("Current File is: %s" % file)

2 个答案:

答案 0 :(得分:2)

一般情况下,请勿使用+创建路径。使用更聪明的os.path.join

shutil.copy(os.path.join(dir_src, filename), dir_dst)

这将为您C:\...\folder\file而不是C:\...\folderfile

或者,您可以使用pathlib

import pathlib
import shutil

dir_src = pathlib.Path(r'C:\Users\Tibi\Desktop\New Folder\New Folder')
dir_dst = pathlib.Path(r'D:\test')

for file in dir_src.rglob('*.CR2'):
    shutil.copy(str(file), str(dir_dst / file.name))

如果您无论案件是否需要匹配,请使用此'*.[Cc][Rr]2'代替'*.CR2'

答案 1 :(得分:1)

在两者之间添加路径分隔符以防止C:\\New FolderIMG_5221.CR2不存在的文件。改变这个:

dir_src + filename

到此:

dir_src + '\\' + filename

或者这是针对可能不在Windows上的更通用的解决方案:

dir_src + os.path.sep + filename