如何使用python在CSV文件中插入两列?

时间:2017-08-18 12:17:00

标签: python csv

我想在新的csv文件中插入两列。 Question1数据应位于第一列,Question2数据应位于第二列

下面给出的代码给出了这个输出:

['question1']
['a','b','c','d']
['e','f','g']
['h','i','j','k','l']
['question2']
['a','b','c','d','x','y']
['e','f','g','m','n','o','p','q']
['h','i','j','k','l','r','s',]

这是我的代码:

col1=question1.split("\n")
col2=question2.split("\n")
with open("outputFile.csv" , mode="wt", encoding='UTF-8') as out_file:
     w=csv.writer(out_file)
     for row in col1:
         myColumns = row.split("\n")
         print(myColumns)
         w.writerow(myColumns)
     for row in col2:
         myColumns = row.split("\n")
         print(myColumns)
         w.writerow(myColumns)

输出应该是这样的: 问题1应位于csv的第一列,问题2应位于csv文件的第二列

['question1']   ['question2']
['a','b','c','d']  ['a','b','c','d','x','y']
['e','f','g']  ['e','f','g','m','n','o','p','q']
['h','i','j','k','l']  ['h','i','j','k','l','r','s',]

请帮助我如何解决问题..

2 个答案:

答案 0 :(得分:3)

您可以使用pandas

import pandas as pd

question1 = [['1', '1'], ['1', '2', '3'], ['3', '4']]   #question 1 data
question2 = [['is', 'was'], ['i', 'am', 'me'],['yes', 'no']] #question 2 data

df = pd.DataFrame(columns=["question1", "question2"])
df["question1"] = question1
df["question2"] = question2

df.to_csv("output.csv", index=False)
  

output.csv

question1,question2
"['1', '1']","['is', 'was']"
"['1', '2', '3']","['i', 'am', 'me']"
"['3', '4']","['yes', 'no']"

答案 1 :(得分:0)

据我所知,你想要的输出是这样的:     [问题1数据],[问题2数据]     [问题1数据],[问题2数据]     ...

在这种情况下,以下内容将帮助您:

first_column = [['a', 'b'], ['c', 'd', 'e'], ['f', 'g']]   #Populate this with your data from question 1
second_column = [['1', '2'], ['3', '4', '5']]              #Populate this with data from question 2


#Find the shortest and the longest of the lists
(shortest_list, lognest_list) =  (first_column, second_column) if len(first_column) < len(second_column) else (second_column,first_column)


#If the two colmns are guarenteed to be of the same length, then this loop is enough
for i in range(0,len(shortest_list)):
    print(str(first_column[i]) + ", " + str(second_column[i]))

#Handle that the who lists may not be of equal lengths
if len(shortest_list) != len(lognest_list):
    for i in range(len(shortest_list),  len(lognest_list)):
        print(str(lognest_list[i]) + ", ")