To write a Python list to a CSV file, you can use the built-in csv module. Here's an example:

import csv

# define the list
my_list = [
    ['John', 'Doe', 25],
    ['Jane', 'Smith', 30],
    ['Bob', 'Johnson', 40]
]

# open a new CSV file in write mode
with open('my_file.csv', 'w', newline='') as file:
    writer = csv.writer(file)

    # write each row in the list to the CSV file
    for row in my_list:
        writer.writerow(row)

In this example, we define a list called my_list that contains three sub-lists, each representing a row of data. We then open a new CSV file called my_file.csv in write mode using the open() function. We use the csv.writer() function to create a writer object, and then use a for loop to write each row in my_list to the CSV file using the writerow() method. We pass the newline='' argument to the open() function to ensure that the CSV file is written with the correct line endings.

After running this code, you should see a new file called my_file.csv in your current working directory, containing the data from my_list in CSV format.

python-list-to-csv-file

原文地址: http://www.cveoy.top/t/topic/rDy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录