简体   繁体   中英

Python: when I read a CSV file's row and then write it to a separate CSV file, it all goes into one cell

Let's say input.csv has one row like this:

1,2,3,4,5

Let's also say that output.csv is empty, but I want it to contain

numbers:,1,2,3,4,5

I'd use the code:

with open('output.csv', 'w') as out:
    wr = csv.writer(out, delimiter=',', lineterminator = '\n')
    with open('input.csv',"rt") as in:
        for line in csv.reader(in, delimiter=','):
            wr.writerow(['numbers:',line])

However, when I do this, output.csv contains:

 numbers:,"[1,2,3,4,5]"

What am I doing wrong?

writerow takes an array and writes each element of that array to the CSV file. You passed two values: 'numbers:' and an array of what you read from the other file. It's just like you called this:

w.writerow(['a', ['b', 'c', 'd']])

which writes: a,"['b', 'c', 'd']" .

You want just wr.writerow(line)

I think you want to combine 'numbers:' and your line from original file to one list. To do that you can use list concatenation. I would rewrite the last line of your script in the following way:

row = ['numbers:'] + line
wr.writerow(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