csvmodule

import csv def GetCSV(filename): # Returns list of dicts data = [] with open(filename +'.csv','U') as csvfile: reader = csv.DictReader(csvfile) for row in reader: data.append(row) return data # takes 'data' (list of dicts or single dict) and writes to CSV: def WriteCSV(filename, mode, data): # mode = 'w' most common with open(filename + '.csv', mode) 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): # 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: filename = raw_input("Enter Filename: ") # This just pulls data from one csv file and writes to another csvdata = GetCSV(filename) WriteCSV('TestCSV','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.