編寫了一個代碼來執行以下操作: 存在一個包含相同類型文件的文件夾(old_dir)。這些文件具有不同的大小。在程序中,我們必須以MB爲單位指定所需的大小(例如,10 MB)。執行時,程序將隨機文件複製到新的指定文件夾(new_dir)中,直到new_dir的大小等於或大於所需大小(上述示例爲10 MB)。Python的文件複製算法不起作用
在Python的代碼如下:
import os, random, shutil
old_dir = "E:\\Desktop\\607"
new_dir = "E:\\Desktop\\new"
size = 10 * 1024 * 1024
file_list = os.listdir(old_dir)
while sum(os.path.getsize(f) for f in os.listdir(new_dir)) < size:
file = file_list.pop(random.randint(0, len(file_list)))
shutil.copy(old_dir + file, new_dir + file)
文件夾 「607」 包含簡單的名稱001,002 ...(135與50 MB的總規模共計)
.jpg文件運行後返回以下錯誤:
Traceback (most recent call last):
File "E:\Desktop\111.py", line 10, in <module>
shutil.copy(old_dir + file, new_dir + file)
File "C:\Python27\lib\shutil.py", line 119, in copy
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'E:\\Desktop\\607006.jpg'
請您在指出錯誤幫助嗎?
你剛剛錯過文件夾名稱和文件名之間的反斜槓嗎? – L3viathan