Search code examples
pythoncsvtransform

How can I transform csv data in python


I have a csv file that I want to transform. Currently the data looks like this in the csv file

115776 1142 1523 20197 20394 3421 1284 9572 19682 

but I want it to look like this

115776 1142
115776 1523
115776 20197
115776 20394
115776 3421 

.....

any idea on how to achieve this?

I currently wrote a function to get it and it gets it like this

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)

is there any better way to do it where it prints it out I want it?


Solution

  • Read the csv into a python list: Python import csv to list

    And then simply loop over the list with repeating the first index:

    test = [115776, 1142, 1523, 20197, 20394, 3421, 1284, 9572, 19682]
    
    for i in test[1:]:
         print test[0], i