2017-04-04 98 views
0

我有一个我想转换的csv文件。目前,数据看起来像这样的csv文件如何在python中转换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) 

有没有更好的方式来做到这一点它打印出来我需要它?

+0

什么你试过这么远吗? – daniboy000

+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 
+0

OP的第一个输出不是OP想要的。 –

+0

谢谢德米特里,赶上。我现在编辑它。 – bjpreisler