Home > Back-end >  How to edit a CSV file row by row in Python without using Pandas
How to edit a CSV file row by row in Python without using Pandas

Time:02-04

I have a CSV file and when I read it by importing the CSV library I get as the output:

['exam', 'id_student', 'grade']`
['maths', '573834', '7']`
['biology', '573834', '8']`
['biology', '578833', '4']
['english', '581775', '7']`
# goes on...

I need to edit it by creating a 4th column called 'Passed' with two possible values: True or False depending on whether the grade of the row is >= 7 (True) or not (False), and then count how many times each student passed an exam. If it's not possible to edit the CSV file that way, I would need to just read the CSV file and then create a dictionary of lists with the following output:

dict = {'id_student':[573834, 578833, 581775], 'passed_count': [2,0,1]}
# goes on...

Thanks

CodePudding user response:

Try using importing csv as pandas dataframe

import pandas as pd
data=pd.read_csv('data.csv')

And then use:

data['passed']=(data['grades']>=7).astype(bool)

And then save dataframe to csv as:

data.to_csv('final.csv',index=False)

CodePudding user response:

Iterate over input rows, augment the field list of each row with an additional item, and save it back to another CSV:

with open('result.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    
    for row in source_rows:
        csvwriter.writerow(row.append(row[2] >= 7))

source_rows is the iterable that gives you the output you posted.

If you need to replace the original content, use os.remove() and os.rename() to do that.

  •  Tags:  
  • Related