0

I have multiple CSV files and I want to move them to one excel file with different sheets. So, I am looking to add each CSV file to a sheet of excel. If there are 3 CSV files, it should be one Excel file with 3 sheets, and sheet names must be the CSV file name.

What would be the best solution for this?

E_net4
  • 27,810
  • 13
  • 101
  • 139
codewithawais
  • 551
  • 1
  • 6
  • 25
  • 1
    What have you tried so far and what problem you cannot solve? Check [ask]. – buran Jul 04 '22 at 13:39
  • I googled for a solution but couldn't find a specific solution so that's why positing it here since I don't have an idea how to do it. – codewithawais Jul 04 '22 at 13:42

1 Answers1

1

Try:

import pandas as pd
import pathlib

with pd.ExcelWriter('output.xlsx') as writer:
    for filename in pathlib.Path('.').glob('*.csv'):
        df = pd.read_csv(filename)
        df.to_excel(writer, sheet_name=filename.stem, index=False)
Corralien
  • 109,409
  • 8
  • 28
  • 52