循环访问子目录中的文本文件



如何仅迭代目录中的文本文件?到目前为止,我所拥有的是;

for file in glob.glob('*'):
    f = open(file)
    text = f.read()
    f.close()

这有效,但是我必须将.py文件存储在同一个目录(文件夹(中才能使其运行,因此迭代包括.py文件本身。理想情况下,我想指挥的是;

  1. "查看此子目录/文件夹,并遍历其中的所有文件">

或。。。

  1. "查看此目录中的所有文件并迭代扩展名为.txt的文件">

确定我要求的东西相当直截了当,但我不知道如何进行。可能值得我强调的是,我通过反复试验获得了 glob 模块,所以如果这是绕过这种特定方法的错误方法,请随时纠正我!谢谢。

glob.glob函数实际上采用通配模式作为其参数。例如,"*.txt"同时匹配名称以 .txt 结尾的文件。

以下是使用它的方法:

for file in glob.glob("*.txt"):
    f = open(file)
    text = f.read()
    f.close()

但是,如果您想排除某些特定文件,例如.py文件,通配语法不直接支持此功能,如此处所述。

在这种情况下,您需要获取这些文件,并手动排除它们:

pythonFiles = glob.glob("*.py")
otherFiles = [f for f in glob.glob("*") if f not in pythonFiles]

glob.glob()使用与标准类 Unix shell 相同的通配符模式匹配。当然,该模式可用于过滤扩展:

# this will list all ".py" files in the current directory
# (
>>> glob.glob("*.py")
['__init__.py', 'manage.py', 'fabfile.py', 'fixmig.py']

但它也可以用来探索给定的路径,相对的:

>>> glob.glob("../*")
['../etc', '../docs', '../setup.sh', '../tools', '../project', '../bin', '../pylint.html', '../sql']

或绝对值:

>>> glob.glob("/home/bruno/Bureau/mailgun/*")
['/home/bruno/Bureau/mailgun/Domains_ Verify - Mailgun.html', '/home/bruno/Bureau/mailgun/Domains_ Verify - Mailgun_files']

当然,您可以同时执行这两项操作:

>>> glob.glob("/home/bruno/Bureau/*.pdf")
['/home/bruno/Bureau/marvin.pdf', '/home/bruno/Bureau/24-pages.pdf', '/home/bruno/Bureau/alice-in-wonderland.pdf']

解决方案非常简单。

for file in glob.glob('*'):
    if not file.endswith('.txt'):
        continue
    f = open(file)
    text = f.read()
    f.close()

最新更新