从文件夹中打开并读取多个xml文件

时间:2018-09-13 09:16:54

标签: python operating-system glob

  

以下所有者拥有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')

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

因此您需要遍历文件夹中的文件?您可以尝试这样的事情:

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')
相关问题