Python:解析折叠中的所有文件

2024-05-03 02:47:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python循环的帮助下解析文件夹中的所有文件,然后将其存储为数据帧,我使用以下脚本

path='C:\\Users\\manusharma\\Training'

for filename in os.listdir(path):
    tree = ET.parse(filename)
    a = ET.tostring(tree.getroot(), encoding='utf-8', method='text')
    c = a.replace('\n', '')
    df = df.append({'text': c, 'type': 'abc'}, ignore_index=True)

我的路径文件有以下文件

^{pr2}$

每次我运行代码,它都会显示一个错误

IOError: [Errno 2] No such file or directory: 'abc1'

虽然它在那里,我在哪里犯错误?感谢每一个帮助


Tags: 文件数据pathtextin脚本文件夹tree
1条回答
网友
1楼 · 发布于 2024-05-03 02:47:53

os.listdir()只返回文件名(不是完整路径)。在

您可以尝试使用glob.glob(path + '/*.xml')而不是os.listdir(path)

演示:

In [111]: path = 'd:/temp/xml'

In [112]: os.listdir(path)
Out[112]: ['1.xml', '2.xml', '3.xml', 'bla.tmp']

In [113]: glob.glob(path + '/*.xml')
Out[113]: ['d:/temp/xml\\1.xml', 'd:/temp/xml\\2.xml', 'd:/temp/xml\\3.xml']

相关问题 更多 >