简体   繁体   English

Python:当我读取CSV文件的行并将其写入单独的CSV文件时,所有内容都放入一个单元格中

[英]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: 假设input.csv具有这样的一行:

1,2,3,4,5

Let's also say that output.csv is empty, but I want it to contain 我们也说output.csv为空,但我希望它包含

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: 但是,当我这样做时,output.csv包含:

 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. writerow接受一个数组,并将该数组的每个元素写入CSV文件。 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']" . 上面写着: a,"['b', 'c', 'd']"

You want just wr.writerow(line) 您只需要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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM