1

我有一个 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

4 回答 4

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)
于 2013-10-14T14:57:02.513 回答
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

于 2013-10-14T15:05:41.430 回答
1

您的输出文件仅包含纯文本,因此不是 .csv 文件,因此无需使用 acsv.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
于 2013-10-14T16:15:39.990 回答
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
于 2013-10-14T15:07:00.417 回答