The problem: My program reads a CSV file and produces a nested list (because there are no line breaks) and I need to 'repair' the list afterwards before I can go further. The code works, but I am struggling to find a more efficient way and would be interested in any suggestions.
The details:
My program reads a CSV file which has the following format:
hakcke39475728,fjfjalcl689920,vjgjvkv848291, ...
So each item contains of letters and numbers, with a comma as the delimiter and no new lines inbetween. I use csv to read the file and put the result into a list:
import csv
result = []
with open("input.csv", "r", newline="") as f:
reader = csv.reader(f, delimiter=",", quotechar='"')
result = list(reader)
As there are no line breaks, the result is a nested list in the following format:
[['hakcke39475728', 'fjfjalcl689920', 'vjgjvkv848291', '...'], []]
After this, I need to "clean up" and perform an extra step - a for loop - to unnest the list:
output_final = []
for item in result[0]:
output_final.append(item)
To finally get the output I need:
['hakcke39475728', 'fjfjalcl689920', 'vjgjvkv848291', '...']
What would be a more efficient way?
I couldn't figure out how to read the CSV in a different way so that it does not result in a nested list. AFAIK there is no way to set a comma as the EOL character (which would resolve my problem here, as I do not have line endings inbetween my values in the input.
Possibly related questions:
- I found this question, but it's about writing the CSV differently, not reading it and not possible in my case.
- This one is asking for a nested list instead of wanting to get rid of it, but there's no way to reverse-engineer the solution.