Note that there are some explanatory texts on larger screens.

plurals
  1. POWrite key to separate csv based on value in dictionary
    primarykey
    data
    text
    <p>[Using Python3] I have a csv file that has two columns (an email address and a country code; script is made to actually make it two columns if not the case in the original file - kind of) that I want to split out by the value in the second column and output in separate csv files. </p> <pre><code>eppetj@desrfpkwpwmhdc.com us ==&gt; output-us.csv uheuyvhy@zyetccm.com de ==&gt; output-de.csv avpxhbdt@reywimmujbwm.com es ==&gt; output-es.csv gqcottyqmy@romeajpui.com it ==&gt; output-it.csv qscar@tpcptkfuaiod.com fr ==&gt; output-fr.csv qshxvlngi@oxnzjbdpvlwaem.com gb ==&gt; output-gb.csv vztybzbxqq@gahvg.com us ==&gt; output-us.csv ... ... ... </code></pre> <p>Currently my code kind of does this, but instead of writing each email address to the csv it overwrites the email placed before that. Can someone help me out with this?</p> <p>I am very new to programming and Python and I might not have written the code in the most pythonic way, so I would really appreciate any feedback on the code in general!</p> <p>Thanks in advance!</p> <p>Code:</p> <pre><code>import csv def tsv_to_dict(filename): """Creates a reader of a specified .tsv file.""" with open(filename, 'r') as f: reader = csv.reader(f, delimiter='\t') # '\t' implies tab email_list = [] # Checks each list in the reader list and removes empty elements for lst in reader: email_list.append([elem for elem in lst if elem != '']) # List comprehension # Stores the list of lists as a dict email_dict = dict(email_list) return email_dict def count_keys(dictionary): """Counts the number of entries in a dictionary.""" return len(dictionary.keys()) def clean_dict(dictionary): """Removes all whitespace in keys from specified dictionary.""" return { k.strip():v for k,v in dictionary.items() } # Dictionary comprehension def split_emails(dictionary): """Splits out all email addresses from dictionary into output csv files by country code.""" # Creating a list of unique country codes cc_list = [] for v in dictionary.values(): if not v in cc_list: cc_list.append(v) # Writing the email addresses to a csv based on the cc (value) in dictionary for key, value in dictionary.items(): for c in cc_list: if c == value: with open('output-' +str(c) +'.csv', 'w') as f_out: writer = csv.writer(f_out, lineterminator='\r\n') writer.writerow([key]) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload