Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

python code that converts list to csv

  1. User

    python code that converts list to csv

  2. Assistant

    You can use the csv module in Python to convert a list to a CSV file. Here's an example code:

    import csv
    
    def list_to_csv(data, filename):
        with open(filename, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerows(data)
    
    # Example usage
    data = [
    	['Name', 'Age', 'Country'],
    	['John', '25', 'USA'],
    	['Jane', '30', 'Canada']
    ]
    
    list_to_csv(data, 'output.csv')
    

    In this code, the list_to_csv function takes two parameters: data (the list to be converted) and filename (the name of the output CSV file). The function opens the file in write mode and creates a csv.writer object. Then, the writerows method is used to write each row from the input list to the CSV file. Finally, an example usage is provided, where a sample data list is passed to the list_to_csv function, and the output is saved to a file called 'output.csv'.