我正在使用 Python 2.7.x 遍历目录树,在遍历时获取文件和目录大小。我遇到的问题是将别名文件误认为目录,然后抛出“没有这样的文件或目录”的错误。
下面的代码:
def get_size(start_path = '.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
for dirName, subdirList, fileList in os.walk(rootDir, topdown=False):
dirSize = get_size(dirName) #this throws an error on alias files
for fname in fileList:
#do other things
我也尝试了 os.path.isdir() 但这不起作用。此外,我尝试了
return File.FSResolveAliasFile(path, True)[0].as_pathname()
但这似乎并没有提取所有别名文件。
有什么想法吗?