0

Just trying to learn python and trying to help a friend with taking a column from a .csv file to print it with a label-maker. The first problem I came across is this:

I will use this example file: test.csv

1111,2222,3333,4444
aaaa,bbbb,cccc,dddd
aaaa,bbbb,cccc,dddd

I run it trough:

import csv

with open('test.csv', 'r') as csv_File:
csv_reader = csv.reader(csv_File)

with open('test2.csv', 'w') as new_file:
    csv_writer = csv.writer(new_file)

    for line in csv_reader:
        (csv_writer).writerow(line[1])

and get the output:

2,2,2,2
b,b,b,b
b,b,b,b

I want the output:

2222
bbbb
bbbb

what am I doing wrong?

1

2 Answers 2

1

writerow is expecting a whole list to write as a row, just as you got a whole list from the reader. To output one field only you should wrap it in a list:

csv_writer.writerow([line[1]])

But note it would be simpler to just write the data directly, since you don't need any of the functionality that the CSV writer gives you:

with open('test2.csv', 'w') as new_file:
    for line in csv_reader:
        new_file.write(line[1])
Sign up to request clarification or add additional context in comments.

Comments

0

writerow takes a iterable of data of one row. You provide it a single string that gets interpreted as iterable and each element gets printed as column.

Fix:

csv_writer.writerow([line[1]])  # put the string into a list so you provide a single item row

Comments

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.