Python把路径中的多个csv文件合并成多个sheet,sheet名为相应表名的代码
时间: 2024-05-06 15:21:43 浏览: 158
可以参照以下代码实现:
```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将路径中的多个cvs文件,有乱码,先转换为正常的文本,在进行转换为多个sheet表,sheet表的名字对应相应的表名的代码
好的,我知道了。对于您的问题,可以使用Python中的pandas库来处理。以下是大致的代码实现:
```
import os
import pandas as pd
# 读取csv文件转换为dataframe,处理乱码
def read_csv_file(path):
df = pd.read_csv(path, encoding='utf-8')
return df
# 将dataframe写入excel文件的sheet表中
def write_to_sheet(df, excel_writer, sheet_name):
df.to_excel(excel_writer, sheet_name=sheet_name, index=False)
# 获取所有csv文件的路径
def get_all_csv_paths(dir_path):
csv_paths = []
for file in os.listdir(dir_path):
if file.endswith('.csv'):
csv_path = os.path.join(dir_path, file)
csv_paths.append(csv_path)
return csv_paths
# 主程序
def main():
csv_dir_path = 'path/to/csv/dir'
excel_file_path = 'path/to/excel/file.xlsx'
excel_writer = pd.ExcelWriter(excel_file_path)
# 处理所有csv文件
csv_paths = get_all_csv_paths(csv_dir_path)
for csv_path in csv_paths:
df = read_csv_file(csv_path)
file_name = os.path.splitext(os.path.basename(csv_path))[0]
sheet_name = file_name.encode('latin1').decode('gbk') # 转换成gbk编码的sheet名
write_to_sheet(df, excel_writer, sheet_name)
excel_writer.save()
if __name__ == '__main__':
main()
```
以上代码实现了将指定文件夹中的多个csv文件转换为excel文件的多个sheet表,sheet表的名字对应相应的表名的功能。其中,read_csv_file函数处理了文件的乱码问题,write_to_sheet函数将dataframe写入sheet表中,get_all_csv_paths函数获取指定文件夹中所有csv文件的路径,main函数是主程序入口,调用以上函数完成功能。
阅读全文
相关推荐













