【发布时间】:2021-10-24 14:50:40
【问题描述】:
尝试将所有 jpg 和 jpeg 文件从 C:\ 驱动器复制到桌面上的备份目录。 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)
【问题讨论】:
-
究竟是什么不起作用?除了您的代码之外,您能否提供更多信息?
-
欢迎来到 Stack Overflow。请阅读How to Ask。我看到了您正在尝试做的事情的声明和一些代码。你有问题吗?这段代码在哪些方面无法实现您的目标?
-
@js-on 我认为这条线不起作用:file_size = os.path.getsize(file)
-
我猜您的问题是您将字节与“千字节”进行比较,os.path.getsize 返回字节,而您的 if 与 50 字节匹配,而不是千字节;)
-
docs.python.org/3/library/os.path.html -> os.path.getsize(path) 返回路径的大小,以字节为单位。如果文件不存在或不可访问,则引发 OSError。
标签: python python-3.x python-3.7