Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing last row in csv

Tags:

python

csv

I'm trying to remove the last row in a csv but I getting an error: _csv.Error: string with NUL byte

This is what I have so far:

dcsv = open('PnL.csv' , 'a+r+b')
cWriter = csv.writer(dcsv, delimiter=' ')
cReader = csv.reader(dcsv)
for row in cReader:
    cWriter.writerow(row[:-1])

I cant figure out why I keep getting errors

like image 925
Rtrader Avatar asked Feb 21 '23 05:02

Rtrader


1 Answers

I would just read in the whole file with readlines(), pop out the last row, and then write that with csv module

import csv
f = open("summary.csv", "r+w")
lines=f.readlines()
lines=lines[:-1]

cWriter = csv.writer(f, delimiter=',')
for line in lines:
    cWriter.writerow(line)
like image 139
reptilicus Avatar answered Feb 25 '23 16:02

reptilicus