【问题标题】:Open and read multiple xml files from the folder从文件夹中打开并读取多个 xml 文件
【发布时间】:2019-02-17 23:58:27
【问题描述】:

以下持有者有 100 多个 XML 文件。我必须打开并阅读所有这些文件。

F:\Process\Process_files\xmls

到目前为止,我执行以下代码从文件夹中打开单个 XML 文件。我需要更改以从文件夹中打开/读取所有 XML 文件。

from bs4 import BeautifulSoup
import lxml
import pandas as pd

infile = open("F:\\Process\\Process_files\\xmls\\ABC123.xml","r")
contents = infile.read()
soup = BeautifulSoup(contents,'html.parser')

【问题讨论】:

    标签: python operating-system glob


    【解决方案1】:

    使用globos 模块迭代给定path 中具有给定文件扩展名的每个文件:

    import glob
    import os
    
    path = "F:/Process/Process_files/xmls/"
    
    for filename in glob.glob(os.path.join(path, "*.xml")):
        with open(filename) as open_file:
            content = open_file.read()
    
        soup = BeautifulSoup(content, "html.parser")
    

    提示:使用with 语句以便文件在最后自动关闭。

    来源: Open Every File In A Folder

    【讨论】:

      【解决方案2】:

      所以你需要遍历文件夹中的文件?你可以试试这样:

      for file in os.listdir(path):
          filepath = os.path.join(path, file)
          with open(filepath) as fp:
              contents = fp.read()
              soup = BeautifulSoup(contents, 'html.parser')
      

      【讨论】:

        猜你喜欢
        • 2019-02-14
        • 1970-01-01
        • 2018-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-11
        • 2014-05-30
        • 1970-01-01
        相关资源
        最近更新 更多