Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete some rows of a CSV, in-place

Tags:

python

csv

This:

import csv
with open('original.csv', 'rb') as inp, open('new.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)
os.remove('original.csv')
os.rename('new.csv', 'original.csv')

allows to delete certain rows of a CSV.

Is there a more pythonic way to delete some rows of a CSV file, in-place? (instead of creating a file, deleting the original, renaming, etc.)

like image 350
Basj Avatar asked Jan 04 '17 00:01

Basj


1 Answers

There isn't a more Pythonic way: you can't delete stuff in the middle of a file. Write out a new file with the stuff you want, and then rename it.

like image 112
Ned Batchelder Avatar answered Oct 10 '22 11:10

Ned Batchelder