1

是否存在一些常用的方法来枚举给定文件夹中的所有文件(以及可选的文件夹,可选地使用子目录递归)?所以我传递了一个文件夹路径并获取结果完整路径的列表。

如果您展示如何从此结果中排除所有只读文件和所有隐藏文件,那就更好了。所以输入参数:

  • dir:文件夹的完整路径
  • option_dirs:包括目录路径到列表
  • option_subdirs:同时处理 dir 的所有子目录
  • option_no_ro:排除只读文件
  • option_no_hid:排除隐藏文件

蟒蛇2。

4

1 回答 1

5

您可能应该研究os.walkand os.access

对于实际实现,您可以执行以下操作:

import os

def get_files(path, option_dirs, option_subdirs, option_no_ro, option_no_hid):
    outfiles = []
    for root, dirs, files in os.walk(path):
        if option_no_hid:
            # In linux, hidden files start with .
            files = [ f for f in files if not f.startswith('.') ]
        if option_no_ro:
            # Use os.path.access to check if the file is readable
            # We have to use os.path.join(root, f) to get the full path
            files = [ f for f in files if os.access(os.path.join(root, f), os.R_OK) ]
        if option_dirs:
            # Use os.path.join again
            outfiles.extend([ os.path.join(root, f) for f in files ])
        else:
            outfiles.extend(files)
        if not option_subdirs:
            # If we don't want to get subdirs, then we just exit the first
            # time through the for loop
            return outfiles
    return outfiles
于 2013-07-22T21:43:32.520 回答