Python遍历文件夹EXCEL 并合并数据
时间: 2024-03-12 16:45:29 浏览: 122
可以使用Python中的pandas库来实现遍历文件夹中的Excel文件并合并数据。
首先,需要导入pandas库和os库:
```python
import pandas as pd
import os
```
然后,定义一个函数来遍历文件夹中的Excel文件并合并数据:
```python
def merge_excel_files(folder_path, output_path):
files = os.listdir(folder_path)
df_list = []
for file in files:
if file.endswith('.xlsx') or file.endswith('.xls'):
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
df_list.append(df)
merged_df = pd.concat(df_list)
merged_df.to_excel(output_path, index=False)
```
其中,`folder_path`是Excel文件所在文件夹的路径,`output_path`是合并后的Excel文件的保存路径。
函数中首先使用`os.listdir()`函数获取文件夹中的所有文件,然后利用`if`语句判断文件是否为Excel文件。如果是Excel文件,则使用`pandas`库中的`read_excel()`函数读取Excel文件,并将数据存储在一个DataFrame中。最后,使用`pd.concat()`函数将所有的DataFrame合并为一个,并使用`to_excel()`函数将合并后的数据保存为一个Excel文件。
调用该函数即可实现遍历文件夹中的Excel文件并合并数据:
```python
folder_path = 'path/to/folder'
output_path = 'path/to/merged/excel/file.xlsx'
merge_excel_files(folder_path, output_path)
```
阅读全文
相关推荐

















