Because I can never, ever, remember exactly how to code these. Example of both, basic.
data_list = [] with open(input_file, 'rU') as f: data_file = csv.DictReader(f) for line in data_file: data_list.append(line) # gets you a list of dicts the_header = ['h1', 'h2', 'etc'] # column headers, a list of text strings with open(output_file, 'w') as f: file_writer = csv.DictWriter(f, fieldnames=the_header) file_writer.writeheader() for line in data_list: file_writer.writerow(line)Here I am going to experiment linking it as a script-tagged element from Gist via GitHub:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Because I always forget exactly how to do these. | |
# Note that in function calls the exact code will be a little different (may need additional code). | |
# Reading | |
data_list = [] # Will be output, list of dicts. | |
with open(input_file, 'rU') as f: | |
data_file = csv.DictReader(f) | |
for line in data_file: | |
data_list.append(line) # Gets you a list of dicts. | |
# Writing | |
the_header = ['h1', 'h2', 'etc'] # Your column headers, a list of text strings. These are placeholders. | |
with open(output_file, 'w') as f: # Don't forget your output file has to have a location/name. | |
file_writer = csv.DictWriter(f, fieldnames=the_header) | |
file_writer.writeheader() | |
for line in data_list: # data_list is the list of dicts you are writing. | |
file_writer.writerow(line) | |
# Done! |