How To Create Multiple Sheets In Csv Using Python

CSV (stands for Comma Separated Values) is one of the most used data exchange formats. It allows to store data in a plain text format separated by commas.

Sometimes it is necessary to create multiple sheets in a CSV file. In this tutorial, you will learn how to create multiple sheets in CSV files using Python.

Step 1: Import Required Libraries

In order to create multiple sheets in CSV files, we need to import specific libraries. In this case, we will need to import “csv” and “pandas” libraries. You can import these libraries by using the following code:

Step 2: Create Your Data

Before creating multiple sheets in CSV files, we need to create our data. In this example, we will create two different sheets containing different data. You can create your data as per your requirement.

Step 3: Create CSV File Using Pandas

In order to create CSV files, we can use the pandas library. The following code shows how to create multiple sheets in a CSV file:

The above code creates a new Excel workbook named “example.csv”. We have converted the sheets into dataframes using the pandas library. Finally, we have added both sheets to the workbook using the “to_excel()” function and saved the workbook.

Step 4: Verify the CSV File

After running the above code, you can check the CSV file in the directory where you have saved it. You will see two different sheets in the CSV file with the following data:

Sheet1:

| Name | City | Country |
|------|------|---------|
| John | New York | USA |
| Mike | Perth | Australia |
| Daniele | Rome | Italy |

Sheet2:

| Food | Price |
|------|-------|
| Pizza | 10 |
| Burger | 12 |
| Sandwich | 8 |

Conclusion

In this tutorial, we have learned how to create multiple sheets in CSV files using Python. We have used the pandas library to create our CSV file. By using this method, you can create multiple sheets in a CSV file as per your requirement with just a few lines of code.

Full Code:

Output:

example.csv file containing two sheets.