generate csv with custom rows in python

To generate a CSV file with custom rows in Python, you can use the csv module. Here's an example:

main.py
import csv

data = [
    ['Name', 'Age', 'Country'],
    ['John', 25, 'USA'],
    ['Alice', 30, 'Canada'],
    ['Bob', 28, 'Australia']
]

filename = 'custom_rows.csv'

with open(filename, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

print(f'CSV file "{filename}" has been generated with custom rows.')
342 chars
17 lines

In this example, we first import the csv module. We then define our custom rows as a nested list data. Each inner list represents a row in the CSV file.

Next, we specify the filename for the CSV file using the filename variable.

We open the file using open() in write mode and the newline='' argument to ensure the proper handling of line endings in different platforms.

We create a writer object using csv.writer(file), passing the file object as an argument. Then, we use the writerows() method to write all the rows in the data list to the CSV file.

Finally, we print a message indicating that the CSV file has been generated.

Make sure to adjust the data list with your custom rows and the filename variable with the desired name for the CSV file.

related categories

gistlibby LogSnag