1

I have a question here:

Write a function named computed_column that takes a string as a parameter representing the name of a CSV file with 5 columns in the format <string>,<int>,<int>,<int>,<int> and writes a file named creation.csv containing all the data from the input file but with a sixth column containing the sum of the values from the third and second columns.

This is what I tried:

    import csv
    def computed_column(csvfile):
    with open(csvfile,newline='') as f:
      with open('creation.csv','w',newline='') as f2:
        y=[]
        writer = csv.writer(f2)
        rows = csv.reader(f)
        for row in rows:
          for i in range(0,len(row[1])):
            y.append(int(row[1][i]) + int(row[2][i]))
          writer.writerow(row+y)

It writes the original file correctly but gives me wrong output for the sixth column that is to be written.

1 Answer 1

1

If I'm understanding your question correctly, you don't need the inner for-loop. For each row, you simply want to add the values in the second and third column (of that row), and insert the sum as the sixth column value. You just need to loop through each row, then use the row index to access the second and third columns.

Also, your list y is growing with each row you process (which adds an additional column each time). I don't think that is your intention. Move this within your for-loop so that it resets to an empty list with each row. Try something like this:

def computed_column(csvfile):
    with open(csvfile,newline='') as f:
        with open('creation.csv','w',newline='') as f2:
            writer = csv.writer(f2)
            rows = csv.reader(f)
            for row in rows:
                y=[]
                y.append(int(row[1]) + int(row[2]))
                writer.writerow(row+y)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.