Python os.walk 和符号链接
Python os.walk and symlinks
在修复一个用户的 answer on 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'
那么问题是,我如何告诉 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 = os.path.join(subdir, f)
if os.path.isfile(file_path):
space += os.stat(file_path).st_size
sys.stdout.write("Total: {:d}\n".format(space))
$> python test_code2.py $HOME
Total: 76763501905
正如 Antti Haapala 在评论中提到的那样,脚本不会在符号链接上中断,而是在 损坏的符号链接 上中断。以现有脚本为起点,避免这种情况的一种方法是使用 try/except
:
#! /usr/bin/python2
import os
import sys
space = 0L # L means "long" - not necessary in Python 3
for root, dirs, files in os.walk(sys.argv[1]):
for f in files:
fpath = os.path.join(root, f)
try:
space += os.stat(fpath).st_size
except OSError:
print("could not read "+fpath)
sys.stdout.write("Total: {:d}\n".format(space))
作为副作用,它会为您提供有关可能损坏链接的信息。
是的,os.path.isfile
是正确的选择。然而,以下版本 可能 内存效率更高。
for subdir, dirs, files in os.walk(sys.argv[1]):
paths = (os.path.join(subdir, f) for f in files)
space = sum(os.stat(path).st_size for path in paths if os.path.isfile(path))
在修复一个用户的 answer on 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'
那么问题是,我如何告诉 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 = os.path.join(subdir, f)
if os.path.isfile(file_path):
space += os.stat(file_path).st_size
sys.stdout.write("Total: {:d}\n".format(space))
$> python test_code2.py $HOME
Total: 76763501905
正如 Antti Haapala 在评论中提到的那样,脚本不会在符号链接上中断,而是在 损坏的符号链接 上中断。以现有脚本为起点,避免这种情况的一种方法是使用 try/except
:
#! /usr/bin/python2
import os
import sys
space = 0L # L means "long" - not necessary in Python 3
for root, dirs, files in os.walk(sys.argv[1]):
for f in files:
fpath = os.path.join(root, f)
try:
space += os.stat(fpath).st_size
except OSError:
print("could not read "+fpath)
sys.stdout.write("Total: {:d}\n".format(space))
作为副作用,它会为您提供有关可能损坏链接的信息。
是的,os.path.isfile
是正确的选择。然而,以下版本 可能 内存效率更高。
for subdir, dirs, files in os.walk(sys.argv[1]):
paths = (os.path.join(subdir, f) for f in files)
space = sum(os.stat(path).st_size for path in paths if os.path.isfile(path))