使用Python从文件夹中依次读取多个Excel文件

问题描述 投票:0回答:2

我有一个文件夹,其中包含多个xls和xlsx格式的excel文件,我正在尝试读取它们并将它们连接在一个单独的Dataframe中。我面临的问题是python无法以正确的顺序读取文件夹中的文件。

我的文件夹包含以下文件:190.xls,195.xls,198.xls,202.xlsx,220.xlsx等等

这是我的代码:

import pandas as pd
from pathlib import Path

my_path = 'my_Dataset/'

xls_files = pd.concat([pd.read_excel(f2) for f2 in Path(my_path).rglob('*.xls')], sort = False)

xlsx_files = pd.concat([pd.read_excel(f1) for f1 in Path(my_path).rglob('*.xlsx')],sort = False)

all_files = pd.concat([xls_files,xlsx_files],sort = False).reset_index(drop=True))

我得到了我想要的东西,但是文件没有按顺序连接,因为它们在文件夹中!意味着在all_files数据帧中,我首先具有来自202.xlsx的数据,然后是来自190.xls的数据]

我该如何解决这个问题?预先谢谢!

python excel pandas sorting concat
2个回答
0
投票

尝试使用

import pandas as pd
from pathlib import Path

my_path = 'my_Dataset/'
all_files = pd.concat([pd.read_excel(f) for f in sorted(list(Path(my_path).rglob('*.xls')) + list(Path(my_path).rglob('*.xlsx')), key=lambda x: int(x.stem))],sort = False).reset_index(drop=True) 

0
投票

更新此

all_files = pd.concat([xls_files,xlsx_files],sort = False).reset_index(drop=True))

至此

all_files = pd.concat([xlsx_files,xls_files],sort = False).reset_index(drop=True))
© www.soinside.com 2019 - 2024. All rights reserved.