将具有特定文件大小的文件复制到桌面路径

Copy files with specific file size to Desktop path

尝试将C:\ 盘中的所有jpg 和jpeg 文件复制到桌面上的备份目录。 jpg 和 jpeg 文件应等于或大于 50 KB。

但是我得到了这个错误:

return os.stat(filename).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified:





 import os
    import shutil
    
    #Create Directory if don't exist in Desktop path
    dir_name = "Backup"
    dir_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
    #dir_path = os.path.expanduser("~/Desktop")
    file_path = os.path.join(dir_path, dir_name)
    
    if not os.path.exists(file_path):
        os.mkdir(file_path)
        print(file_path)
    
    try:
            path = r'C:\'
            extensions = [".jpg", ".jpeg"]
            for root, dir, files in os.walk(path):
                    for file in files:
                            if file.endswith(extensions[0]) or file.endswith(extensions[1]):
                                    file_size = os.path.getsize(file)
                                    if file_size >= 50:
                                            print('File size:', file_size, 'KB')
    
                                            shutil.copy2(os.path.join(root,file), file_path)
                                            print(f"File==> {file}")
    
    
    except KeyboardInterrupt:
        print("Quite program!!!")
        time.sleep(5)
        os._exit(0)

file_size = os.path.getsize(file)替换为

file_size = os.path.getsize(os.path.join(root,file))

编辑

import os
import shutil
import time

#Create Directory if don't exist in Desktop path
dir_name = "Backup"
dir_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
#dir_path = os.path.expanduser("~/Desktop")
file_path = os.path.join(dir_path, dir_name)

if not os.path.exists(file_path):
    os.mkdir(file_path)
    print(file_path)

try:
        path = r'C:\'
        extensions = [".jpg", ".jpeg"]
        for root, dir, files in os.walk(path):
                for file in files:
                        if file.endswith(extensions[0]) or file.endswith(extensions[1]):
                                file_size = os.path.getsize(os.path.join(root,file))
                                if file_size <= 50000:
                                        print('File size:', file_size, 'KB')

                                        shutil.copyfile(os.path.join(root,file), os.path.join(file_path,file))
                                        print(f"File==> {file}")


except KeyboardInterrupt:
    print("Quite program!!!")
    time.sleep(5)
    os._exit(0)