Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

python to csv

  1. User

    python to csv

  2. Assistant

    To export data from Python to a CSV file, you can use the csv module. Here's an example of how you can do this:

    import csv
    
    data = [
        ['Name', 'Age', 'City'],
        ['John', 30, 'New York'],
        ['Jane', 25, 'Los Angeles'],
        ['Alex', 35, 'London']
    ]
    
    filename = 'data.csv'
    
    with open(filename, 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(data)
    
    print(f'{filename} has been created successfully.')
    

    In this example, the data variable represents the data that you want to export. It is a list of lists, where each inner list represents a row in the CSV file.

    The filename variable holds the name of the CSV file you want to create. You can change it to suit your needs.

    The with open(filename, 'w', newline='') as file: statement opens the file in write mode. The newline='' parameter ensures that newlines are handled correctly across platforms.

    The csv.writer(file) creates a writer object to handle writing data to the CSV file.

    The writer.writerows(data) method writes the data to the CSV file.

    Finally, the print statement informs you when the file has been created successfully.

    Make sure to replace the example data with your own data to save it to a CSV file.