【问题标题】:Ignore "System Volume Information" in Python listdir忽略 Python listdir 中的“系统卷信息”
【发布时间】:2019-10-22 07:29:40
【问题描述】:

我目前正在尝试获取 Windows 卷上的所有文件,以便复制某些文件。从一个文件夹复制到另一个文件夹可以正常工作,但是当尝试列出目录然后遍历卷的找到的文件时,我只是受到“系统卷信息”的访问被拒绝异常的欢迎。

如何在循环中忽略/跳过这个?

我正在使用递归函数,第一次使用卷本身的根路径调用它。

def list_all(path):
files = os.listdir(path)

for file in files:
    low_path = os.path.join(path, file)

    if os.path.isdir(low_path):
        list_all(low_path)
    else:
        # shutil.copy()

【问题讨论】:

    标签: python windows listdir


    【解决方案1】:

    您可以添加try/except

    def list_all(path):
    files = os.listdir(path)
    
    try:
      files.remove("System Volume Information")
    except:
      print("System Volume Information not present in this directory")
    
    
    for file in files:
        low_path = os.path.join(path, file)
    
        if os.path.isdir(low_path):
            list_all(low_path)
        else:
            # shutil.copy()
    

    【讨论】:

      【解决方案2】:

      RMPR 的回答对手头的问题很有帮助(项目列表中只有一个例外)。

      如果将 try/except 移动到循环内,则循环可以更通用,以跳过“拒绝访问”的所有实例(WindowsImageBackup 是一个常见示例,还有其他示例)。

      def list_all(path):
          files = os.listdir(path)
      
      
          for file in files:
              low_path = os.path.join(path, file)
              try:
                  if os.path.isdir(low_path):
                      list_all(low_path)
                  else:
                      # shutil.copy()
              except:
                  print("Directory ",low_path, " has denied access.")
       
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-05
        • 2011-04-07
        • 2012-02-09
        • 1970-01-01
        • 2019-02-17
        • 2010-11-09
        • 2010-10-02
        • 1970-01-01
        相关资源
        最近更新 更多