1

I am trying to add headers to existing csv files using a python script. I found a way to do it but it uses too much of my memory and causes my laptop to crash. I wanted to know if there's a better way to do it. I will post the code below.

#!/usr/bin/env python3

import csv

with open('MBAc.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('MBAc.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['student_number', 'State_Studentnumber', 'Attendance_codeid', 'Att_code', 'att_date', 'att_mode_code', 'SchoolID', 'YearID','Att_Comment'])
    w.writerows(data)
Rodrigo
  • 11
  • 1
  • Don't pull the whole csv into memory. Instead, write to another file line by line. After that is done, `mv` the new file to the old name – juanpa.arrivillaga Feb 28 '22 at 18:00
  • As an aside, `[line for line in r]` is an unnecessarily complicated way of doing `list(r)`, but again, you want to avoid doing this to save memory – juanpa.arrivillaga Feb 28 '22 at 18:03
  • I'm still relatively new to python. How do I do this? – Rodrigo Feb 28 '22 at 18:06
  • Why not just write the header into the file? Try the second approach of [this answer](https://stackoverflow.com/a/5917395/225020) – Jab Feb 28 '22 at 18:13
  • I get the files from someone else and it's multiple files I need to add the headers to. It would take too much time. – Rodrigo Feb 28 '22 at 18:21

0 Answers0