【问题标题】:How to try open files unless no exception?除非没有例外,否则如何尝试打开文件?
【发布时间】: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 循环。
  • 为了提高效率,我会列出所有出现权限被拒绝错误的文件名,然后在完成所有可用文件后分别处理它们。就你的时间等待逻辑而言,这里有一些很好的答案,所以我认为你会管理

标签: python loops exception


【解决方案1】:

通过在 while True 循环中使用 try catch 块包围打开的文件,并在 PermissionError 出现时等待 n 秒。但是要小心,如果您不想跳过文件,则必须确保 PermissionError 只是暂时的,否则您最终会陷入不断重试的无限循环(我会在 之后实现中断以停止n 次尝试)

import glob, time
 filenames = glob.glob('*.csv')
 for file in filenames:
     while True:
         try:
             hndl = open(file,"rb")
             # Do stuff
             break
         except PermissionError:
             time.sleep(5)
             hndl.close()
             continue
         
     
 


    

【讨论】:

    【解决方案2】:

    根据@Michael Butscher 的评论,我做了一些更改。 (归功于他)

    顺便说一句,代码从来没有失败过两次。

    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
            while True: # infinite loop
                with open(path + fs, "rb") as f:
                    try:
                        next(f) # skip the header
                        fout.write(f.read())
                        #status
                        sys.stdout.write('\r') # overwrite in place
                        expectedTime = round((((time.time() - startTime)/(toLoad.index(fs)+1))*(len(toLoad) - toLoad.index(fs)))/60,2) # based on how it went so far 
                        percentage = round((toLoad.index(fs)/(len(toLoad)+1))*100,2)  # number of done files relative to all files (after date filter)
                        success = success + 1 # counter
                        sys.stdout.write('completed {} perc. expected time to end: {} minutes, success: {}, failed: {}'.format(percentage, expectedTime, success, failed)) # status
                        sys.stdout.flush()
                        failed = 0 # reset counter if success
                        break
                    except PermissionError:
                        #second try always works. Script waits 5 seconds and usually run ok.
                        failed = failed + 1 # counter
                        print('\n Perm error, trying again in 5 sec. ({})'.format(path + fs))
                        time.sleep(5)
            if failed > 10: 
                print('\n Script failed more than 10 time so I stopped it.')
                break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 2015-02-10
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      相关资源
      最近更新 更多