create a csv file in python

To create a CSV file in Python, you can use the csv module built into Python's standard library. Here's an example of creating a new CSV file named "example.csv" and writing some data to it:

main.py
import csv

# define your data
data = [
    ['Name', 'Age', 'Gender'],
    ['John', 25, 'Male'],
    ['Jane', 33, 'Female'],
    ['Bob', 50, 'Male']
]

# open the file in writing mode
with open('example.csv', 'w', newline='') as file:

    # create the csv writer
    writer = csv.writer(file)

    # write the data to the csv file
    for row in data:
        writer.writerow(row)
382 chars
20 lines

In this example, we first define the data we want to write to the CSV file as a list of lists. Each inner list represents a row in the CSV file, with the first row containing column headers.

Then, we open the file using open() and passing in the file name 'example.csv', along with the mode 'w' for writing. We also pass in newline='' to avoid extra blank lines between rows.

After that, we create the csv writer using csv.writer(), passing in the file object.

Finally, we loop through the data and write each row to the CSV file using writer.writerow().

gistlibby LogSnag