Python把路径中的多个csv文件合并成多个sheet,sheet名为相应表名的代码
时间: 2024-05-06 12:21:43 浏览: 16
可以参照以下代码实现:
```python
import pandas as pd
import glob
# 获取所有csv文件的路径
path = r"path\to\csv\files\*.csv"
csv_files = glob.glob(path)
writer = pd.ExcelWriter('output.xlsx')
# 循环处理每个csv文件
for csv_file in csv_files:
# 从文件名中提取表名
table_name = csv_file.split('\\')[-1].split('.')[0]
# 读取csv文件数据
data = pd.read_csv(csv_file)
# 将数据写入excel文件中对应的sheet
data.to_excel(writer, sheet_name=table_name, index=False)
writer.save()
```
以上代码中,我们使用了`glob`库来获取所有csv文件的路径,然后循环遍历每个csv文件。对于每个文件,我们从文件名中提取表名,并读取csv文件中的数据。最后,我们将数据写入excel文件中对应的sheet中,sheet名为表名。
相关问题
Python把路径中的excel格式是CVS的文件合并成多个sheet,sheet名为相应的表名的代码
可以使用 pandas 模块中的 read_csv() 和 ExcelWriter() 函数来实现。代码如下:
```
import pandas as pd
# 读取CSV文件
df = pd.read_csv('path/to/file.csv')
# 按照表名分组
groups = df.groupby('表名')
# 创建ExcelWriter对象
writer = pd.ExcelWriter('path/to/output/file.xlsx')
# 循环写入每个表的数据
for name, group in groups:
group.to_excel(writer, sheet_name=name, index=False)
# 保存Excel文件
writer.save()
```
这段代码会将 CSV 文件读取为 DataFrame 对象,然后按照表名分组,并创建一个 ExcelWriter 对象。最后循环写入每个表的数据到 Excel 文件中,每个表对应一个 sheet,sheet 名称为表名。
python合并多个csv为一个excel的多个sheet
可以使用 pandas 库来合并多个 CSV 文件,并将它们保存为一个 Excel 文件的多个 sheet。以下是一个示例代码:
```python
import pandas as pd
# 假设有三个 CSV 文件:file1.csv、file2.csv 和 file3.csv
file_names = ['file1.csv', 'file2.csv', 'file3.csv']
# 读取每个 CSV 文件,并将它们存储在一个列表中
dfs = [pd.read_csv(filename) for filename in file_names]
# 创建一个 Excel 写入器
writer = pd.ExcelWriter('output.xlsx')
# 将每个 DataFrame 存储为 Excel 的一个 sheet
for i, df in enumerate(dfs):
df.to_excel(writer, sheet_name=f'Sheet{i+1}', index=False)
# 保存 Excel 文件
writer.save()
```
这个代码会将三个 CSV 文件合并到一个名为 `output.xlsx` 的 Excel 文件中,并将它们分别存储在名为 `Sheet1`、`Sheet2` 和 `Sheet3` 的 sheet 中。你可以根据需要修改代码,以适应你的具体情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)