访问目录列表中每个文件的pythonic方式

标签 python

我的工作代码如下所示:

# Wow. Much nesting. So spacebar
if __name__ == '__main__:
  for eachDir in list_of_unrelated_directories:
      for eachFile in os.listdir(eachDir):
          if eachFile.endswith('.json'):
            # do stuff here

我想知道是否有更优雅的方式来做到这一点。我不想让我的代码像那样深嵌套三层,如果我能把它变成像这样的单行代码

for each file that ends with .json in all these directories:
  # do stuff

那会更棒。我还对此进行了编辑以指出目录并不都在同一个文件夹中。就像您可能在主文件夹和/tmp 文件夹中查找 .json 文件一样。所以我不会尝试在单个文件夹中递归移动。

最佳答案

(在我看来)最 Pythonic 的方法是编写一个生成特定类型文件的函数并使用它。然后你的调用代码非常清晰简洁。其他一些答案非常简洁但令人难以置信的困惑;在你的实际代码中,你应该重视清晰而不是简洁(尽管当你能同时获得这两者时,当然是首选)。

函数如下:

import os

def files_from_directories(directories, filetype):
    """Yield files of filetype from all directories given."""
    for directory in directories:
        for file in glob.glob(os.path.join(directory, '*' + filetype))
            yield file

现在您的调用代码真的是一行:

# What a good one-liner!!!!
for json_file in files_from_directories(directories, '.json'):
    # do stuff

所以现在你有了一条线,一条非常清晰的线。另外,如果您想要处理任何其他类型的文件,您可以只对不同的文件类型重用该函数。

关于访问目录列表中每个文件的pythonic方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22690519/

相关文章:

python - 如何在 python 中确保输入参数不是复值而是实值

python - 使用 Python 对矩阵进行切片

python - 我正在用 Python 创建一个以 Twitch 为中心的 IRC 机器人,但它得到响应的速度很慢。我究竟做错了什么?

python - 如何在Python中实现良好的移动平均线

python - OpenCV 对象跟踪输入格式

python - 如何在 Python 中向量化这些嵌套循环?

python - 对数据库多次运行 "python manage.py syncdb"可以吗?

python - "Select a valid choice."在 Django 中使用 Modelform 时出错

python - 如何使用 Python 查找字符串中重叠序列的数量?

python - Django 。我怎样才能在模型中做一些数学运算