Skip to content

Instantly share code, notes, and snippets.

@amberj
Created October 21, 2023 04:26
Show Gist options
  • Save amberj/29d7b55a29b9a5582158e3b6b65a82b1 to your computer and use it in GitHub Desktop.
Save amberj/29d7b55a29b9a5582158e3b6b65a82b1 to your computer and use it in GitHub Desktop.
Write Python list as a row to CSV
#!/usr/bin/env python3
import csv
def write_row_to_csv(filename, row_data_as_list, file_mode):
with open(filename, file_mode, newline='') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
# writing the data rows
csvwriter.writerow(row_data_as_list)
header = ["Name","Country", "Age", "Gender"]
data = [
["Tom", "USA", "33", "M"],
["Penelope", "USA", "31", "F"]
]
#################
# Sample usage: #
#################
write_row_to_csv("test-file.csv", header, "w")
write_row_to_csv("test-file.csv", data[0], "a")
write_row_to_csv("test-file.csv", data[1], "a")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment