【问题标题】:How can I skip an OS error so that my for-loop does not break?如何跳过操作系统错误以使我的 for 循环不会中断?
【发布时间】:2020-10-14 12:16:31
【问题描述】:

我有一个函数可以成功获取顶层文件夹的所有文件路径。但是,当它遇到我无权访问的文件夹时,循环会中断。

如何跳过此错误,以便在不中断循环的情况下提取所有其余文件路径?

我正在考虑使用tryexcept,但我不确定如何实现。有什么想法吗?

这是我的代码:

def get_list_of_files(dir_name):
    """
    Gets all the filepaths. 
    :param: dir_name: the name of the directory to parse 
    : return all of the filepaths 
    """
    list_files = os.listdir(dir_name)
    all_files = list()      
    
    for item in list_files:
        full_path = os.path.join(dir_name, item)
        if os.path.isdir(full_path):
            all_files = all_files + get_list_of_files(full_path)
        else:
            all_files.append(full_path)
    return all_files

【问题讨论】:

  • 请查看 try/except 块,这将为您指明正确的方向
  • 当然,如果不先查一下,我不会问这个问题。在 for 循环的顶部实现“尝试”是否可行,除了: OSError ?欢呼
  • 哪个语句中断/给出错误?

标签: python function loops directory try-catch


【解决方案1】:

您可以使用os.path.walk,它似乎可以将您没有权限的文件/目录排除在外,并带有内置递归:

drwxr-xr-x   4 foobar  wheel   128B Oct 14 14:25 .
drwxrwxrwt  15 root    wheel   480B Oct 14 14:30 ..
drwx------   2 root    wheel    64B Oct 14 14:25 bar
-rw-r--r--   1 foobar  wheel     0B Oct 14 14:25 foo.txt

...目录bar 只能被root 用户读取。

def get_list_of_files(dir_name):
    all_files = []
    for dirpath, subdirs, files in os.walk(dir_name):
        for file in files:
            all_files.append(os.path.join(dirpath, file))
    return all_files

files = get_list_of_files('/tmp/test')
print(files)

输出:

['/tmp/test/foo.txt']

【讨论】:

    【解决方案2】:

    在下面试试这个,基本上,它使用“try, except”,使代码“try”照常执行,当他遇到 OSError 异常时,他开始执行“except”下的东西,这是我的示例,传递到 list_files 中的下一项。

    list_files = os.listdir(dir_name)
    all_files = list()      
    
    for item in list_files:
        try:
            full_path = os.path.join(dir_name, item)
            if os.path.isdir(full_path):
                all_files = all_files + get_list_of_files(full_path)
            else:
                all_files.append(full_path)
        except OSError:
            # maybe some other code you want to execute
            continue
    return all_files
    

    【讨论】:

      【解决方案3】:

      使用except OSError

      这可以让你走上正轨:

      for number in range(-1,3):
          try:
              print(1/number)
          except ZeroDivisionError:
              pass
      
      # -1.0
      # notice how 0 is simply skipped because it gets caught by except
      # 1.0
      # 0.5
      

      在您提到不确定如何实现它之后,人们可能会考虑将整个 for loop 放在 try except 块中,结果是:

      try:
          for item in range(-1,3):
              print(1/item)
      except ZeroDivisionError:
          print('This gets printed when the first error is caught and the loop stops')
      
      # -1.0
      # This gets printed when the first error is caught and the loop stops
      

      【讨论】:

      • OP 已经提到他们知道 try/except
      • OP 表示她/他不确定如何实施。
      • 不推荐使用裸except
      猜你喜欢
      • 2013-01-22
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      • 2012-12-13
      • 2013-02-01
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多