1

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?

1
  • The output you desire isn't CSV - so I've answered based on just creating a line that can be used Commented Oct 14, 2013 at 15:00

4 Answers 4

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, I should've been clearer in my question! I was looking to output I love {c} and {e} into a separate file. Thanks Jon!
1

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

Comments

1

Your output file consists of just plain text, is therefore not a .csv file, so there's no need to use a csv.DictWriterto create it. It's also easy to redirect aprintstatement'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

Comments

0

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

1 Comment

Thanks Vivek, that works! Now I understand how this works better. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.