【问题标题】:Python CSV - Combine, clean and to output emails in correct formatPython CSV - 合并、清理并以正确格式输出电子邮件
【发布时间】:2016-06-30 02:30:51
【问题描述】:

我正在尝试获取超过 1 个包含姓名、电子邮件地址等信息的文件。从 CSV 格式获取这些文件并删除除电子邮件之外的所有内容。然后在同一行上输出一个带有分号分隔符的新文件。 最终格式应如下所示:

someone@hotmail.com; someoneelse@gmail.com; someone3@university.edu

我必须检查电子邮件的alphanumeric@alphanumeric.3letters 格式是否正确。 我必须删除所有重复项。 我必须将此列表与另一个列表进行比较,并从 1 个列表中删除其他列表中出现的电子邮件。

最终格式将是这样的,有人可以将电子邮件收件人地址复制并粘贴到 Outlook 中。

我看过一些视频。也在这里。我找到了:python csv copy column

但在尝试写入新文件时出现错误。 我有import csv and re

下面是我的代码:

def final_emails(email_list):
  with open(email_list) as csv_file:
    read_csv = csv.reader(csv_file, delimiter=',')

    write_csv = csv.writer(out_emails, delimiter=";")

    for row in read_csv:
        email = row[2]  # only take the emails (from column 3)
        if email != '':  # remove empties

            # remove the header, or anything that doesn't have a '@'
            # convert to lowercase and append to list
            emails.append(re.findall('\w*@\w*.\w{3}', email.lower()))
            write_csv.write([email])
  return emails


final_emails(list1)
final_emails(list2)


print(emails)

我有打印在底部检查。 我添加了写入来制作新文件,但是这个错误 TypeError: 参数 1 必须有一个“写”方法

我还在努力学习。这次我做了很多以前没有做的事情,比如 csv 和正则表达式。 请提供任何帮助。谢谢你。

【问题讨论】:

    标签: python regex email csv


    【解决方案1】:

    您需要将out_emails定义为具有可写权限的文件句柄,然后才能在csv.writer中使用它

    csv.writer 需要一个具有.write 属性(如文件句柄)的对象才能写入它。 out_emails 似乎没有 .write 属性。

    【讨论】:

    • 我对 out_emails 的定义如下所示:out_emails = r"\\path\to\file.csv"
    • out_emails 必须是文件句柄,类似于out_emails = open(r"\\path\to\file.csv", 'w')
    猜你喜欢
    • 1970-01-01
    • 2016-08-26
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    相关资源
    最近更新 更多