如何在python中转换csv数据

时间:2017-04-04 18:43:39

标签: python csv transform

我有一个我要转换的csv文件。目前,csv文件中的数据如下所示

115776 1142 1523 20197 20394 3421 1284 9572 19682 

但我希望它看起来像这样

115776 1142
115776 1523
115776 20197
115776 20394
115776 3421 

.....

关于如何实现这一目标的任何想法?

我目前编写了一个函数来获取它,它就像这样得到它

for row in read_csv(testfile, "Recipes_RecipeId Recipes_Ingredients_0_IngredientID Recipes_Ingredients_1_IngredientID Recipes_Ingredients_2_IngredientID Recipes_Ingredients_3_IngredientID Recipes_Ingredients_4_IngredientID Recipes_Ingredients_5_IngredientID Recipes_Ingredients_6_IngredientID Recipes_Ingredients_7_IngredientID Recipes_Ingredients_8_IngredientID".split()):
    with open('recipeIngredientID.csv', 'a') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(row)

是否有更好的方法可以将它打印出来,我想要它?

1 个答案:

答案 0 :(得分:0)

将csv读入python列表:Python import csv to list

然后简单地循环遍历列表并重复第一个索引:

test = [115776, 1142, 1523, 20197, 20394, 3421, 1284, 9572, 19682]

for i in test[1:]:
     print test[0], i