在修复一位用户在 AskUbuntu 上的回答时 ,我发现了一个小问题。代码本身很简单: os.walk ,递归地获取目录中所有文件的总和。
但它打破了符号链接:
$ python test_code2.py $HOME
Traceback (most recent call last):
File "test_code2.py", line 8, in <module>
space += os.stat(os.path.join(subdir, f)).st_size
OSError: [Errno 2] No such file or directory: '/home/xieerqi/.kde/socket-eagle'
Run Code Online (Sandbox Code Playgroud)
那么问题是,我如何告诉 python 忽略这些文件并避免对它们求和?
解决方案:
正如评论中所建议的,我添加了os.path.isfile()检查,现在它可以完美运行并为我的主目录提供正确的大小
$> cat test_code2.py
#! /usr/bin/python
import os
import sys
space = 0L # L means "long" - not necessary in Python 3
for subdir, dirs, files in os.walk(sys.argv[1]):
for f in files:
file_path = …Run Code Online (Sandbox Code Playgroud)