[英]How to split a column with integer values in csv file to a new columns
I have a one column of numbers, like 22,23,25,32,33,36. 我有一列数字,例如22、23、25、32、33、36。 and I want to split it new columns in csv file such that first column has 22, second column 23 and so on. 我想将其拆分为csv文件中的新列,以便第一列为22,第二列为23,依此类推。
import csv
from csv import writer
COLUMNS = 6
with open("Winning No - Sheet1.csv", "r") as input:
with open("output_file.csv", "w") as f:
output = writer(f, delimiter=";")
output.writerow(["Col {}".format(i+1) for i in xrange(COLUMNS)])
buffer = []
for row in input:
buffer.append(row)
if len(buffer) == COLUMNS:
output.writerow(row.split(','))
del buffer[:]
When I tried this, I get 6 columns with all the numbers in it such that first column with 22,23,25,32,33,36. 当我尝试此操作时,我得到6列,其中包含所有数字,因此第一列为22、23、25、32、33、36。 Second column with another six numbers. 第二列还有另外六个数字。 How to sort this out? 如何解决呢?
Output that I want: 我想要的输出:
COL1 COL2 COL3 COL4 COL5 COL6
22 23 25 32 33 36
Output that I get is actually: 我得到的输出实际上是:
COL1 COL2 COL3 COL4 COL5 COL6
22,23...,36 1,3,,...,36 3,4,...9 4,6,...7 8,9,...10 1,2,....7
You probably want to do something like: 您可能想要执行以下操作:
output.writerow(row.split(','))
I've never used the csv module, but it looks like it also provides a reader which you could use to do the parsing. 我从未使用过csv模块,但看起来它还提供了一个读者,您可以用来进行解析。
Updated with more context: 更新了更多上下文:
with open("Winning No - Sheet1.csv", "r") as input:
with open("output_file.csv", "w") as f:
output = writer(f, delimiter=";")
output.writerow(["Col {}".format(i+1) for i in xrange(COLUMNS)])
for row in input:
output.writerow(row.split(','))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.