Portedbowl Real
Portedbowl Real

Reputation: 11

How to remove delimiters when reading csv file in Python?

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?

Upvotes: 0

Views: 2493

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599610

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

Upvotes: 1

Patrick Artner
Patrick Artner

Reputation: 51653

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

Upvotes: 0

Related Questions