![](/img/trans.png)
[英]How do I take specific tables from a CSV and write a new file in Python?
[英]How to take inputs from a CSV file and write a specific output with Python?
我有一个包含以下数据的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列的数据中。我该怎么做?
您可以使用字符串格式设置并提供由csv.DictReader
返回的row
对象,例如:
with open('routes2.csv', 'rb') as csvfilein:
reader = csv.DictReader(csvfilein)
for row in reader:
print 'I love {c} and {e}'.format(**row)
像这样?
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
您的输出文件仅包含纯文本,因此不是.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
尝试:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.