Skip to content

Instantly share code, notes, and snippets.

@devstar0209
Last active March 4, 2024 02:16
Show Gist options
  • Save devstar0209/701127f1bcb70783687eac23935ebafa to your computer and use it in GitHub Desktop.
Save devstar0209/701127f1bcb70783687eac23935ebafa to your computer and use it in GitHub Desktop.
Write to CSV file using python
# Write data to CSV file using csv lib
import csv
header = ['Name', 'M1 Score', 'M2 Score']
data = [['Alex', 62, 80], ['Brad', 45, 56], ['Joey', 85, 98]]
filename = 'Students_Data.csv'
with open(filename, 'w', newline="") as file:
csvwriter = csv.writer(file) ## 2. create a csvwriter object
csvwriter.writerow(header) ## 4. write the header
csvwriter.writerows(data)
# using .writelines()
with open(filename, 'w') as file:
for header in header:
file.write(str(header)+', ')
file.write('n')
for row in data:
for x in row:
file.write(str(x)+', ')
file.write('n')
# Using Pandas
import pandas as pd
data = pd.DataFrame(data, columns=header)
data.to_csv('Stu_data.csv', index=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment