[英]Convert CSV file with values spareted in comma to multi columns CSV file
I want to create a small program to convert a CSV file with one column containing values separated by comma, to CSV file containing multiple columns with one value: 我想创建一个小程序,将包含一列包含逗号分隔值的CSV文件转换为包含多列包含一个值的CSV文件:
input file: 输入文件:
output file: 输出文件:
Therefor I write this code: 为此,我编写以下代码:
my_string1 = 'A,B,C,D,E'
my_string2 = 'A,B,C,D,E'
my_string3 = 'A,B,C,D,E'
my_list1 = my_string1.split(",")
my_list2 = my_string2.split(",")
my_list3 = my_string3.split(",")
path = 'C:\Dokumente\\n_1.csv'
rows = zip(my_list1,my_list2,my_list3)
with open(path, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for row in rows:
for column in row:
writer.writerow('%s;' % column)
But the problem is that it writes all the values in one Column. 但是问题在于它会将所有值写入一列。
I want to write column by column and then I want to move to second row to write again? 我想逐列写,然后想移至第二行再次写?
I work with Eclipse Oxy with PyDev and Python 2.7 我在PyDev和Python 2.7中使用Eclipse Oxy
There are two problems with your code. 您的代码有两个问题。 Firstly, there is no need to use
zip()
, instead you should create a list of lists by simply rows = [my_list1,my_list2,my_list3]
. 首先,不需要使用
zip()
,而是应该仅通过rows = [my_list1,my_list2,my_list3]
创建列表列表。 The difference between the two can be seen by printing the result: 可以通过打印结果看出两者之间的差异:
rows_zip = zip(my_list1,my_list2,my_list3)
rows_list = [my_list1,my_list2,my_list3]
print (list(rows_zip))
#[('A', 'A', 'A'), ('B', 'B', 'B'), ('C', 'C', 'C'), ('D', 'D', 'D'), ('E', 'E', 'E')]
print (rows_list)
#[['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]
Secondly, you need to pass the whole list my_list1
into writer.writerow()
as this writes the whole row of the csv file. 其次,您需要将整个列表
my_list1
到writer.writerow()
因为这将写入csv文件的整个行。 Therefore, you only need one loop, which iterates through your list of lists: 因此,您只需要一个循环,即可循环访问列表清单:
my_string1 = 'A,B,C,D,E'
my_string2 = 'A,B,C,D,E'
my_string3 = 'A,B,C,D,E'
my_list1 = my_string1.split(",")
my_list2 = my_string2.split(",")
my_list3 = my_string3.split(",")
path = 'C:\Dokumente\\n_1.csv'
rows = [my_list1,my_list2,my_list3]
with open(path, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for row in rows:
writer.writerow(row)
save it as an excel file, CSV is by definition one column separated by commas, colons, etc. In your code you are splitting a string, and then writing them again separating by commas, undoing what you just did before. 将其保存为Excel文件,根据定义,CSV是一列,以逗号,冒号等分隔。在代码中,您将拆分字符串,然后再次以逗号分隔将其写入,以撤消之前的操作。
You could just use pandas, load the CSV file and save it to excel format 您可以只使用熊猫,加载CSV文件并将其保存为Excel格式
df=pandas.read_csv("file.csv")
df.to_excel(filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.