import csv
'''
For use in other scripts, simply;
import csvmodule
Then call functions like this:
csvmodule.GetCSV('filename') #returns a list of dicts
csvmodule.WriteCSV('filename', data) #data must be list of dicts or single dict
'''
def GetCSV(filename):
#Ingest CSV / return a list of dictionaries
data = []
with open(filename +'.csv','U') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
return data
# take 'data' (list of dicts or single dict) and write to CSV:
def WriteCSV(filename, data): # mode = 'w' most common
with open(filename + '.csv', 'w') as output_file:
if type(data) is list:
keys = KeyGetter(data)
writer = csv.DictWriter(output_file, fieldnames=keys)
writer.writeheader()
writer.writerows(data)
elif type(data) is dict:
fieldnames = data.keys()
writer = csv.DictWriter(output_file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(data)
else:
print "--Unsupported data type--"
def KeyGetter(ListOfDicts):
# CALLED ONLY BY WriteCSV function
# Grab all Keys from a list of dicts
# Normalizes column headers from multiple dicts
# Returns a list of keys (aka column headers)
fields = []
# Iterate through all dicts to grab all keys:
for each_dict in ListOfDicts:
# dump all keys into one big list:
all_keys = [y for y in each_dict.keys()]
# Only add one copy of each key to fields list:
for each_key in all_keys:
if each_key not in fields:
fields.append(each_key)
else:
pass
return fields
'''
# Test it out as a script:
filename = raw_input("Enter Filename: ")
# This just pulls data from one csv file and writes to another
csvdata = GetCSV(filename)
WriteCSV('OutPutFile','w',csvdata)
'''
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.