I am reading a csv into a list, and I need to delete an entire line from the list under a specific condition:
import csv
thefile = []
def dowork():
sourceFile='e.csv'
CleanFile(sourceFile)
def CleanFile(sourceFile):
global thefile
thefile=list(csv.reader(open(sourceFile, 'rb'), delimiter=',', quotechar='"'))
for line in thefile:
if line[3]=='':
#here's where i need to delete line from thefile
how would i delete line from thefile?
You need the index of
linewithinthefile. Once you have that, it’s easy. And the way you get that is with enumerate.However, it’s worth asking whether you actually need to delete it. For example, could you just filter it out like this?
Or, depending on what you’re doing with the data, maybe it makes even more sense to just skip over lines where
line[3] == ''at output or calculation time. Or, even better, don’t make a list in the first place; just leave csv.reader as an iterator—then you can stick a filter in front of it viaitertools.ifilter, or a generator expression. In fact, that’s as simple as just changing two characters:Of course this makes no sense if you need, e.g., random access to
thefile. But if you’re going to iterate over it line by line, this is probably the best solution. (Except thatthefileshouldn’t be a global; it should be passed around from function to function as needed.)