[使用 Python3] 我有一个 csv 文件,它有两列(一个电子邮件地址和一个国家/地区代码;如果原始文件中不是这种情况,脚本实际上使它成为两列 - 有点),我想通过第二列中的值并在单独的 csv 文件中输出。
eppetj@desrfpkwpwmhdc.com us ==> output-us.csv
uheuyvhy@zyetccm.com de ==> output-de.csv
avpxhbdt@reywimmujbwm.com es ==> output-es.csv
gqcottyqmy@romeajpui.com it ==> output-it.csv
qscar@tpcptkfuaiod.com fr ==> output-fr.csv
qshxvlngi@oxnzjbdpvlwaem.com gb ==> output-gb.csv
vztybzbxqq@gahvg.com us ==> output-us.csv
... ... ...
目前我的代码是这样做的,但不是将每个电子邮件地址写入 csv,而是覆盖之前放置的电子邮件。有人可以帮我解决这个问题吗?
我对编程和 Python 非常陌生,我可能没有以最 Python 的方式编写代码,所以我非常感谢对代码的任何反馈!
提前致谢!
代码:
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])