Note that there are some explanatory texts on larger screens.

plurals
  1. POPrint the count of lines written into CSV file
    primarykey
    data
    text
    <p>[Python3] I have a script that reads a (long) CSV file, containing email addresses and corresponding country codes, and splits these out by country code. This is going fine, but I want the script to print out the number of lines (i.e. emails) (it has written) as per each file.</p> <p>Also, I'm very new to programming and Python so I would be very glad to receive any optimization suggestions or other tips in general!</p> <p>Input file looks something like this:</p> <pre><code>12345@12345.com us xyz@xyz.com gb aasdj@ajsdf.com fr askdl@kjasdf.com de sdlfj@aejf.com nl ... ... </code></pre> <p>The output should look something like this:</p> <pre><code>Done! us: 20000 gb: 20000 de: 10000 fr: 10000 nl: 10000 ... </code></pre> <p>My code is the following:</p> <pre><code>import csv, datetime from collections import defaultdict """ Script splits a (long) list of email addresses with associated country codes by country codes. Input file should have only two columns of data - ideally. """ # Declaring variables emails = defaultdict(list) in_file = "test.tsv" # Write filename here. filename = in_file.split(".") """Checks if file is comma or tab separated and sets delimiter variable.""" if filename[1] == "csv": delimiter = ',' elif filename[1] == "tsv": delimiter = '\t' """Reads csv/tsv file and cleans email addresses.""" with open(in_file, 'r') as f: reader = csv.reader(f, delimiter=delimiter) for row in reader: # Gets rid of empty rows if row: # Gets rid of non-emails if '@' in row[0]: # Strips the emails from whitespace and appends to the 'emails' list # Also now 'cc' is in the first position [0] and email in the second [1] emails[row[1].strip()].append(row[0].strip()+'\n') """"Outputs the emails by cc and names the file.""" for key, value in emails.items(): # Key is 'cc' and value is 'email' # File is named by "today's date-original file's name-cc" with open('{0:%Y%m%d}-{1}-{2}.csv'.format(datetime.datetime.now(), filename[0], key), 'w') as f: f.writelines(value) </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.
 

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