将值以逗号保留的CSV文件转换为多列CSV文件 [英] Convert CSV file with values spareted in comma to multi columns CSV file

查看:82
本文介绍了将值以逗号保留的CSV文件转换为多列CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个小程序,将包含一列包含逗号分隔值的CSV文件转换为包含多列包含一个值的CSV文件:

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:

输入文件:

输出文件:

为此,我编写以下代码:

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?

我通过PyDev和Python 2.7使用Eclipse Oxy

I work with Eclipse Oxy with PyDev and Python 2.7

推荐答案

您的代码有两个问题.首先,不需要使用 zip(),而是应该仅通过 rows = [my_list1,my_list2,my_list3] 创建列表列表.通过打印结果可以看出两者之间的区别:

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]. 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']]

第二,您需要将整个列表 my_list1 传递到 writer.writerow()中,因为这将写入csv文件的整个行.因此,您只需要一个循环,即可循环访问列表清单:

Secondly, you need to pass the whole list my_list1 into writer.writerow() as this writes the whole row of the csv file. 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)

这篇关于将值以逗号保留的CSV文件转换为多列CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆