文件结构
我有一个名为 test_folder 的文件夹,它有几个子文件夹(在下面的代码中可以看到,名称不同的水果名称)。在每个子文件夹中,始终有一个 metadump.xml 文件,我从中提取信息。
当前立场
我已经能够在个人基础上实现这一点,我指定子文件夹路径。
import re
in_file = open("C:/.../Downloads/test_folder/apple/metadump.xml")
contents = in_file.read()
in_file.close()
title = re.search('<dc:title rsfieldtitle="Title"
rsembeddedequiv="Name" rsfieldref="8" rsfieldtype="0">(.+?)</dc:title>',
contents).group(1)
print(title)
后续步骤
我想通过简单地引用父文件夹 C:/.../ Downloads / test_folder 并使我的程序找到每个子文件夹的xml文件以提取所需的更大规模来执行以下功能信息,而不是单独指定每个水果子文件夹。
澄清
我希望物理访问这些子文件夹,以便从每个子文件夹中的每个xml文件中执行此文本提取功能,而不是简单地获取子文件夹列表或这些子文件夹中的xml文件列表。
提前感谢您的帮助。
答案 0 :(得分:2)
您可以使用os.listdir作为以下内容:
ReportParameter
答案 1 :(得分:2)
如果您不确定文件夹中的子文件夹数量,可以使用glob模块执行此操作。 recursive=True
将检查文件夹C:/../Downloads/test_folder/
中的所有子文件夹,并为您提供所有metadump.xml
个文件的列表
import re
import glob
for file in glob.glob("C:/**/Downloads/test_folder/**/metadump.xml", recursive=True):
with open(file) as in_file:
contents= in_file.read()
title = re.search('<dc:title rsfieldtitle="Title"
rsembeddedequiv="Name" rsfieldref="8" rsfieldtype="0">(.+?)</dc:title>',
contents).group(1)
print(title)
答案 2 :(得分:1)
这可能会对您有所帮助:
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".xml"):
print(os.path.join(root, file))
答案 3 :(得分:1)
您可以使用Python的os.walk()
遍历所有子文件夹。如果文件是metadump.xml
,它将打开它并提取您的标题。显示文件名和标题:
import os
for root, dirs, files in os.walk(r"C:\...\Downloads\test_folder"):
for file in files:
if file == 'metadump.xml':
filename = os.path.join(root, file)
with open(filename) as f_xml:
contents = f_xml.read()
title = re.search('<dc:title rsfieldtitle="Title" rsembeddedequiv="Name" rsfieldref="8" rsfieldtype="0">(.+?)</dc:title>', contents).group(1)
print('{} : {}'.format(filename, title))