【问题标题】:Python Reading high number of files in a directory, and processing, Fast way?Python读取目录中的大量文件并进行处理,快速方式?
【发布时间】:2019-08-05 05:44:00
【问题描述】:

我在 a 目录中有近 5000 多个 xml 文件。我打算一一阅读并解析它们,但是我不确定 os.listdir(path) 是一个好方法,

import xml.etree.ElementTree as ET  
import os

list_files = os.listir(os.curdir)
for files in list_files:
   tree = ET.parse(files)
   root = tree.getroot()

os.listdir(path) 返回一个包含该目录内文件名称的列表。之后使用 for 循环获取文件的字符串名称并将它们提供给 Parser 类对象可能不是一个好方法,因为解析器会再次搜索文件,第二次,它们的名称在同一目录中。

有没有更好的方法?我是否遗漏了什么,也许是用于查找内部目录的指针逻辑?

编辑: 我认为这个问题离题了,应该删除,因为解析器不会在目录中搜索字符串名称,换句话说,我相信操作系统会在后面处理它。正如您可以在 Parser 的 ET 对象中的以下行,它直接打开

def parse(self, source, parser=None):
    close_source = False
    if not hasattr(source, "read"):
        source = open(source, "rb")
        close_source = True

【问题讨论】:

  • 也许您可以更清楚地了解您在寻找什么。您的示例解析每个文件(第一个近似值),但您似乎想找到一个特定的文件。你想建立索引吗?没有它,扫描所有文件似乎是唯一的方法。
  • 我想解析所有这些,但是在您列出并 for 循环列表之后,它会从列表中获取字符串,并再次在 5000+ 文件目录中搜索第二次,我相信这很昂贵
  • 如果您不遍历列表,您还建议如何解析每个文件
  • 它不会 - for files in list_files 循环遍历路径字符串,因此它直接转到该文件,解析它并开始读取 XML。它不会在任何地方搜索它。如果你想访问所有文件,那么这是最快的方法。

标签: python list directory


【解决方案1】:

请检查这个 python3.5:https://docs.python.org/3/library/os.html#os.scandir python2:https://pypi.org/project/scandir/

try:
    from os import scandir, walk
except ImportError:
    from scandir import scandir, walk


def subdirs(path):
    for entry in scandir(path):
        if entry.name.endswith('.xml') and  entry.is_file(): // change your restriction
            yield entry.name



for i in subdirs('/tmp'):
    print i # you get file name here, 
    //ET.parse(i)

【讨论】:

  • 我相信你告诉我scandir返回一个很棒的路径对象,我怎样才能给xml解析器提供路径?
  • try: from os import scandir, walk except ImportError: from scandir import scandir, walk def subdirs(path): """产生不以'.'开头的目录名在给定路径下。""" 用于 scandir(path) 中的条目:if entry.is_file(): yield entry.name for i in subdirs('/tmp'): print i
  • 如何将路径对象提供给 xml 解析器?
【解决方案2】:

您可以采取一些步骤来读取 XML 文件:

第 1 步: 解析列表中的所有当前目录 XML 文件

import xml.etree.ElementTree as ET  
import os
items = os.listdir(".")

xmllist = []
for names in items:
    if names.endswith(".xml"):
        xmllist.append(names)
print(xmllist)

第 2 步:

现在想读取 xmllist 文件

for files in xmllist:
    tree = ET.parse(files)
    root = tree.getroot()
    print(root)

[注意:如果您有更多疑问,请离开 cmets]

【讨论】:

  • 与我的问题中的代码有什么区别
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 2021-07-29
  • 2018-11-11
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多