【问题标题】:how to read multiple values from a field in csv file using python 3如何使用python 3从csv文件中的字段中读取多个值
【发布时间】:2017-09-14 13:13:02
【问题描述】:

您好,我有一个这样用逗号分隔的 csv 文件。

name, email1; Email2; email3, etc, telephone

我想使用 python 中的 csv 模块从电子邮件字段中提取所有电子邮件地址。并从每个电子邮件地址使用像这样的其他字段写一行

name, email1, etc, telephone
name, Email2, etc, telephone
name, email3, etc, telephone

也许我需要阅读电子邮件字段并将其拆分为单独的字符串?

【问题讨论】:

  • 是的,也许你会。实施它,然后在遇到问题时提出问题。

标签: python python-3.x csv multiple-value


【解决方案1】:

创建一个 CSV 读取器和写入器,如您所说,使用标准 , 分隔符读取文件,然后使用 ; 手动拆分电子邮件字段。对于每个电子邮件条目,写下其他字段:

import csv

with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    for row in csv_input:
        emails = row[1].split(';')
        for email in emails:
            csv_output.writerow([row[0], email]  + row[3:])

或者稍微紧凑一点:

import csv

with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)

    for row in csv.reader(f_input):
        csv_output.writerows([row[0], email] + row[3:] for email in row[1].split(';'))

使用 Python 3.x 测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多