gpt4 book ai didi

python - "OSError: [Errno 2] No such file or directory"表示现有文件

转载 作者:行者123 更新时间:2023-12-01 02:43:35 25 4
gpt4 key购买 nike

我正在尝试迭代一些目录,我必须返回文件夹的总大小。但是,我收到此错误

OSError: [Errno 2] No such file or directory: 

运行代码中的函数后,获取我的文件夹中子目录之一中的文件之一。为什么会发生此错误,即使我的函数正在遍历文件夹,因此该文件必须存在?

def get_size(folder): 
folder_size = 0
for (path, dirs, files) in os.walk(folder):
for file in files:
filename = os.path.join(path, file)
folder_size += os.path.getsize(filename)
return folder_size

最佳答案

在行走过程中出现此错误的一个可能原因是遇到“悬空”符号链接(symbolic link),即链接目标不存在。

要解决此问题,请决定要如何处理悬空链接:

  • 忽略他们?您可以使用 os.path.islink 来检查文件是否是链接。
  • 使用lstat而不是stat,这会将链接的大小作为目标的长度,而不是尝试解析链接。您应该将 os.path.getsize(filename) 替换为 os.lstat(filename).st_size

关于python - "OSError: [Errno 2] No such file or directory"表示现有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45424740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com