2017-04-04 94 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