【发布时间】:2020-11-14 16:13:00
【问题描述】:
我有这段代码来整合文件夹(Box Drive 文件夹)中的数千个 csv 文件,但是有时我会在某些文件上遇到权限错误。当我开始代码时,它很好。但是随着目录中的随机文件,此错误弹出的随机性更少。
我需要做的是等待几秒钟,然后尝试再次打开该文件(不要跳过它)
到目前为止,我有这个但没有按预期工作:
with open(OutputTo, "wb") as fout:
with open(sampleFile, "rb") as f: # first file to get header
fout.write(f.read())
for fs in toLoad: # now the rest
with open(path + fs, "rb") as f:
#while True: # infinite loop
try:
next(f) # skip the header
fout.write(f.read())
except PermissionError:
#second try usually works.
failed = failed + 1 # counter
if failed > 10:
print('\n Script failed more than 10 time so I stopped it.')
break
else:
print('\n Perm error, trying again in 5 sec.')
time.sleep(5)
【问题讨论】:
-
“while True”基本上是正确的想法(但最好将“with”包裹起来而不是放在里面)。如果一切正常,请在 try 块中的代码末尾放置一个“break”以退出循环。应该在 while 循环之外重复检查“失败”计数以打破封闭的 for 循环。
-
为了提高效率,我会列出所有出现权限被拒绝错误的文件名,然后在完成所有可用文件后分别处理它们。就你的时间等待逻辑而言,这里有一些很好的答案,所以我认为你会管理