Rtrader
Rtrader

Reputation: 947

Removing last row in 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

Upvotes: 5

Views: 26982

Answers (3)

zrgt
zrgt

Reputation: 76

This should work

import csv
f = open('Pnl.csv', "r+")
lines = f.readlines()
lines.pop()
f = open('Pnl.csv', "w+")
f.writelines(lines)

Upvotes: 2

martineau
martineau

Reputation: 123393

I'm not sure what you're doing with the 'a+r+b' file mode and reading and writing to the same file, so won't provide a complete code snippet, but here's a simple method to skip any lines that contains a NUL byte in them in a file you're reading, whether it's the last, first, or one in the middle being read.

The trick is to realize that the docs say the csvfile argument to a csv.writer() "can be any object which supports the iterator protocol and returns a string each time its next() method is called." This means that you can replace the file argument in the call with a simple filter iterator function defined this way:

def filter_nul_byte_lines(a_file):
    for line in a_file:
        if '\x00' not in line:
            yield line

and use it in a way similar to this:

dcsv = open('Pnl.csv', 'rb+')
cReader = csv.reader(filter_nul_byte_lines(dcsv))
for row in cReader:
    print row

This will cause any lines with a NUL byte in them to be ignored while reading the file. Also this technique works on-the-fly as each line is read, so it does not require reading the entire file into memory at once or preprocessing it ahead of time.

Upvotes: 0

reptilicus
reptilicus

Reputation: 10397

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)

Upvotes: 8

Related Questions