首页 > 解决方案 > FileNotFoundError 在 Windows 上的 python 中没有扩展文件

问题描述

我在路径中有一个无扩展名文件:C:/Users/example/Downloads。文件名为 examplefile,因此路径将为 C:/Users/example/Downloads/examplefile。我试着用

os.stat("C:/Users/example/Downloads/examplefile").st_size

但我收到了这个错误:

  File "<pyshell#26>", line 1, in <module>
    os.stat(file).st_size
FileNotFoundError: [WinError 2] The specified file could not be found: 'C:/Users/example/Downloads/examplefile' 

所以我尝试使用os.path.getsize()但我仍然遇到同样的错误。我怎样才能获得文件大小?

标签: pythonwindowspython-os

解决方案


在这种情况下,该文件确实具有扩展名 - 它只是在默认配置中不显示它的窗口。

您可以在尝试使用 glob 模式时从 Python 获取真实文件名。

为方便起见,您可能希望使用pathlib, 而不是os,因为它将 glob 功能和 stat 结合在一个地方:


from pathlib import Path

path_to_guess = Path("C:/Users/example/Downloads/examplefile")

path = path_to_guess.parent.glob(path_to_guess.stem + ".*")[0]
print(path)
# here you have the extension. Of course, you might have more than one
# file with the same base name- this is good for a
# one time script or interactive use - 
# for production you should check also creation time, and maybe use
# other means to pick the correct file.
size = path.stat.st_size()

推荐阅读