Convert CSV file with values spareted in comma to multi columns CSV file

穿精又带淫゛_ 提交于 2021-01-28 06:00:12

问题


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:

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


回答1:


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

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)



回答2:


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.

You could just use pandas, load the CSV file and save it to excel format

    df=pandas.read_csv("file.csv")
    df.to_excel(filename)


来源:https://stackoverflow.com/questions/46887098/convert-csv-file-with-values-spareted-in-comma-to-multi-columns-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!