gpt4 book ai didi

python - 使os.walk/os.stat忽略权限被拒绝?

转载 作者:行者123 更新时间:2023-12-03 08:50:28 26 4
gpt4 key购买 nike

我制作了下面的Python 2.4脚本,该脚本扫描了许多LINUX磁盘上的文件,并以易于阅读的格式从os.stat返回了它们的路径和状态。

#!/usr/bin/env python

from datetime import datetime as dt
import os
import grp
import pwd

locations = ["/disk1", "/disk2", "/disk3", "/disk4", "/disk5", "/disk6"]

for item in locations:
for root, dirs, files in os.walk(item):
for fn in files:
path = os.path.join(root, fn)
stats = os.lstat(path)
size = str(stats.st_size)
user = pwd.getpwuid(stats.st_uid)[0]
group = grp.getgrgid(stats.st_gid)[0]
laccess = dt.fromtimestamp(stats.st_atime).strftime("%Y-%m-%d,%H:%M:%S")
lmod = dt.fromtimestamp(stats.st_mtime).strftime("%Y-%m-%d,%H:%M:%S")
c = ","
t1 = ["0,", path, c, size, c, user, c, group, c, laccess, c, lmod,"\n"]
outfile = open("/data/promigrate/DiskDashboard/Temp/filescan.csv", "at")
outfile.write("".join(t1))
outfile.close()

但是,我发现我无权访问系统上的某些文件。

我收到以下错误:
abc12bmm -34> python files_scan.py
Traceback (most recent call last):
File "files_scan.py", line 24, in ?
stats = os.lstat(path)
OSError: [Errno 13] Permission denied: '/disk1/file5'

是否可以通过以下方式处理错误:该过程跳过权限被拒绝的错误并继续到下一个文件?

我一直在玩异常等游戏,但是没有喜悦,所以任何帮助将不胜感激。

谢谢!

贾斯汀

最佳答案

问题是由于os.lstat没有权限在文件上运行,我在错误的位置使用了try-except。要处理该错误,请尝试添加try和except,如下所示。

#!/usr/bin/env python

from datetime import datetime as dt
import os
import grp
import pwd

locations = ["/disk1", "/disk2", "/disk3", "/disk4", "/disk5", "/disk6"]

for item in locations:
for root, dirs, files in os.walk(item):
for fn in files:
path = os.path.join(root, fn)
try:
stats = os.lstat(path)
size = str(stats.st_size)
user = pwd.getpwuid(stats.st_uid)[0]
group = grp.getgrgid(stats.st_gid)[0]
laccess = dt.fromtimestamp(stats.st_atime).strftime("%Y-%m-%d,%H:%M:%S")
lmod = dt.fromtimestamp(stats.st_mtime).strftime("%Y-%m-%d,%H:%M:%S")
c = ","
t1 = ["0,", path, c, size, c, user, c, group, c, laccess, c, lmod,"\n"]
outfile = open("/data/promigrate/DiskDashboard/Temp/filescan.csv", "at")
outfile.write("".join(t1))
outfile.close()
except OSError:
pass

现在可以处理该错误并继续运行。

感谢你的帮助!

关于python - 使os.walk/os.stat忽略权限被拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42343711/

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