I'm reading in a .csv file to a list and it appends an empty lists, I'm using the code below to do this.
with open('Scores.csv', 'r') as scores:
reader = csv.reader(scores)
tscores = [[str(e) for e in r] for r in reader]
It creates a list of nested lists correctly but appends an empty list after every row read in like so:
[[score1, name1], [], [score2, name2], []]
I believe it's reading \n as an empty string which is why I'm getting that, so I tried to remove empty lists using:
tscores = [tscores.remove(x) for x in tscores if x]
which does delete empty nested lists, but it sets all other nested lists that contained data to None i.e. [None, None]. I modified to:
tscores = [tscores.remove(x) for x in tscores if []]
which wipes out all nested lists completely.
How can I read the file with the same output (a list of nested lists) without appending empty lists or how can I remove all empty lists after being read in?
I think what you want to do is
tscores = [x for x in tscores if x != []]
which make a list of only the none empty lists in tscores
Alternative to user2990008's answer, you can not create the empty lists in the first place:
tscores = [[str(e) for e in r] for r in reader if len(r) > 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With