Home > OS >  When i try to remove a row from the csv the file size is multipliying
When i try to remove a row from the csv the file size is multipliying

Time:09-06

I want to create a program which generates numbers from 0 to 100000 and stores it in a file then, remove the numbers i give as input I have done the code for generating the numbers and storing them in a csv file

import csv

nums = list(range(0,100000))
with open('codes.csv', 'w') as f:
    writer = csv.writer(f)
    for val in nums:
        writer.writerow([val])

and i tried to delete the row i wanted with this

import csv
import os

lines = list()
while True:
    members= input("Please enter a number to be deleted: ")

    with open('codes.csv', 'r') as readFile:
        reader = csv.reader(readFile)
        for row in reader:
            lines.append(row)
            for field in row:
                if field == members:
                    lines.remove(row)

    os.remove('codes.csv')

    with open('codes.csv', 'a ') as writeFile:
        writer = csv.writer(writeFile)
        writer.writerows(lines)

but the file size is multiplying each time i remove a number, please help

CodePudding user response:

Add check before appending to your list, something like this should work:

with open('codes.csv', 'r') as readFile:
    reader = csv.reader(readFile)
    for row in reader:
        if all(field != members for field in row):
            lines.append(row)

Ps: don't forget to clear lines by adding lines = [] at the beginning of the while loop (I assume you know what you're doing).

CodePudding user response:

The lines list is never cleared. Whenever a number is entered, everything is written again to lines. Try to recreate the list within the outer while loop, like this:

import csv
import os

while True:
    members= input("Please enter a number to be deleted: ")
    lines = list()

    with open('codes.csv', 'r') as readFile:
        reader = csv.reader(readFile)
        for row in reader:
            lines.append(row)
            for field in row:
                if field == members:
                    lines.remove(row)

    os.remove('codes.csv')

    with open('codes.csv', 'a ') as writeFile:
        writer = csv.writer(writeFile)
        writer.writerows(lines)
  • Related