Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem with your code is that it keeps opening the same country output file each time it writes an entry into it, thereby overwriting whatever might have already been there.</p> <p>A simple way to avoid that is to open all the output files at once for writing and store them in a dictionary keyed by the country code. Likewise, you can have another that associates each country code to a<code>csv.writer</code>object for that country's output file.</p> <p><strong>Update:</strong> While I agree that Burhan's approach is probably superior, I feel that you have the idea that my earlier answer was excessively long due to all the comments it had -- so here's another version of essentially the same logic but with minimal comments to allow you better discern its reasonably-short true length (even with the contextmanager).</p> <pre><code>import csv from contextlib import contextmanager @contextmanager # to manage simultaneous opening and closing of output files def open_country_csv_files(countries): csv_files = {country: open('output-'+country+'.csv', 'w') for country in countries} yield csv_files for f in csv_files.values(): f.close() with open('email.tsv', 'r') as f: email_dict = {row[0]: row[1] for row in csv.reader(f, delimiter='\t') if row} countries = set(email_dict.values()) with open_country_csv_files(countries) as csv_files: csv_writers = {country: csv.writer(csv_files[country], lineterminator='\r\n') for country in countries} for email_addr,country in email_dict.items(): csv_writers[country].writerow([email_addr]) </code></pre>
    singulars
    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.
    1. VO
      singulars
      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