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.py382 chars20 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