python合并文件夹内excel
时间: 2023-09-20 08:06:14 浏览: 58
可以使用Python标准库中的os和pandas模块来实现文件夹内Excel文件的合并。
首先,需要使用os模块获取文件夹中所有Excel文件的路径,可以使用以下代码:
```python
import os
dir_path = "path/to/folder"
files = os.listdir(dir_path)
excel_files = [f for f in files if f.endswith('.xlsx') or f.endswith('.xls')]
file_paths = [os.path.join(dir_path, f) for f in excel_files]
```
然后,可以使用pandas模块中的read_excel函数读取每个Excel文件,并将它们合并成一个数据框。可以使用以下代码:
```python
import pandas as pd
dfs = []
for file_path in file_paths:
df = pd.read_excel(file_path)
dfs.append(df)
merged_df = pd.concat(dfs, ignore_index=True)
```
最后,将合并后的数据框保存到一个新的Excel文件中,可以使用以下代码:
```python
merged_df.to_excel("path/to/new_file.xlsx", index=False)
```
完整代码如下:
```python
import os
import pandas as pd
dir_path = "path/to/folder"
files = os.listdir(dir_path)
excel_files = [f for f in files if f.endswith('.xlsx') or f.endswith('.xls')]
file_paths = [os.path.join(dir_path, f) for f in excel_files]
dfs = []
for file_path in file_paths:
df = pd.read_excel(file_path)
dfs.append(df)
merged_df = pd.concat(dfs, ignore_index=True)
merged_df.to_excel("path/to/new_file.xlsx", index=False)
```
阅读全文
相关推荐














