如何从CSV文件获取输入并使用Python编写特定输出?

时间:2013-10-14 14:53:08

标签: python csv

我有一个包含如下数据的CSV文件:

a,b,c,d,e,f
0,0,AER,0,DME,0
0,0,ASF,0,LED,0

如何从C列和E列获取输入,并将它们输出为:

I like [column C] and [column E]
I like [column C] and [column E]

示例:

I like AER and DME
I like ASF and LED

现在我有以下代码:

import csv

header1 =['c']
header2 =['e']

with open('routes2.csv', 'rb') as csvfilein, open('out.csv', 'wb') as csvfileout:
    reader = csv.DictReader(csvfilein)
    writer1 = csv.DictWriter(csvfileout, header1, extrasaction='ignore')
    writer2 = csv.DictWriter(csvfileout, header2, extrasaction='ignore')
    for line in reader:
        writer1.writerow(line), writer2.writerow(line)

我一直试图弄清楚如何将文本附加到C和E列的数据中。我该怎么做?

4 个答案:

答案 0 :(得分:4)

您可以使用字符串格式并提供row返回的csv.DictReader对象,例如:

with open('routes2.csv', 'rb') as csvfilein:
    reader = csv.DictReader(csvfilein)
    for row in reader:
        print 'I love {c} and {e}'.format(**row)

答案 1 :(得分:1)

喜欢这个吗?

with open('routes2.csv', 'rb') as csvfilein:
reader = csv.DictReader(csvfilein)
for line in reader:
    print "I like %s and %s" % (line["c"], line["e"])

输出:

  

我喜欢AER和DME我喜欢ASF和LED

答案 2 :(得分:1)

您的输出文件只包含纯文本,因此不是.csv文件,因此无需使用csv.DictWriter来创建它。如图所示,将print语句的输出重定向到文件也很容易。

import csv

header1 = ['c']
header2 = ['e']
format_specifier = 'I like %({0[0]})s and %({1[0]})s'.format(header1, header2)

with open('routes2.csv', 'rb') as csvfilein, open('out.txt', 'w') as fileout:
    for row in csv.DictReader(csvfilein):
        print >> fileout, format_specifier % row

答案 3 :(得分:0)

<强>尝试:

import csv
    header1 =['c']
    header2 =['e']

    with open(r'<input_file_path>', 'rb') as csvfilein, open(r'<output_file_path>', 'wb') as csvfileout:
        reader = csv.DictReader(csvfilein)
        for line in reader:
            csvfileout.write("I like "+line.get(header1[0])+" and "+line.get(header2[0])+"\n")

<强>输出:

I like AER and DME

I like ASF and LED