简体   繁体   中英

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?

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

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

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