加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 21:29:52 所属栏目:Python 来源:网络整理
导读:我有工作代码,如下所示: # Wow. Much nesting. So spacebarif __name__ == '__main__: for eachDir in list_of_unrelated_directories: for eachFile in os.listdir(eachDir): if eachFile.endswith('.json'): # do stuff here 我想知道是否有一种更优雅的
我有工作代码,如下所示:
# 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文件一样.所以我不是试图通过单个文件夹递归移动.

解决方法

最恐怖的方式是(在我看来)编写一个函数,它产生某种类型的文件并使用它.然后你的调用代码非常简洁明了.其他一些答案非常简洁但令人难以置信的混乱;在您的实际代码中,您应该重视清晰度而不是简洁(尽管当您可以获得两者时,当然,首选).

这是功能:

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

所以现在你有一个单行,一个非常清楚.此外,如果您要处理任何其他类型的文件,您可以只使用不同的文件类型重用该函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读