简体   繁体   中英

How to take inputs from a CSV file and write a specific output with Python?

I have a CSV file with data like the following:

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

How do I take inputs from columns C and E, and output them into something like:

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

example:

I like AER and DME
I like ASF and LED

Right now I have the following code:

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)

I'm stuck at trying to figure out how to append the text to data from columns C and E. How would I do this?

You can use string formatting and provide the row object returned by csv.DictReader , eg:

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

Like this?

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"])

Output:

I like AER and DME
I like ASF and LED

Your output file consists of just plain text, is therefore not a .csv file, so there's no need to use a csv.DictWriter to create it. It's also easy to redirect a print statement's output to a file as illustrated.

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

Try:

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")

OUTPUT:

I like AER and DME

I like ASF and LED

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM