Hi,
I have a CSV file from which I want to retrieve a specific element, to be precise the one contained in a certain column and in the last row (or the first, starting from the bottom) to have a certain string as the first element. I’ll give a simplified practical example, where instead of a CSV file I use a table, to explain myself better.
I have some ideas about it, but I turn to you: what is the most elegant and efficient way to retrieve the element highlighted in yellow, which is the element in the fourth column of the last row whose first element is Diamond?
I trust in you!
Thanks in advance, and best regards,
Alessia
The simplest method is to read the file using the csv module and then get the value. Don’t worry about whether it’s the most efficient way unless you find that it’s too slow for your purpose in practice.
Thank you all! Actually I had omitted a relevant detail that explained why I had issues finding a solution: the rows of the CSV file are not all complete, some have only one element, others are empty, so reading the column I was interested in I got errors. I solved it by looping through all the rows, examining those that had the value I was looking for in the first column, and extracting the corresponding value from the column I was interested in, with exception handling; at the end of the loop I have the value I was looking for.
import csv
with open('cards.csv') as file_obj:
reader_obj = csv.reader(file_obj)
for row in reader_obj:
try:
if row[0] == 'Diamond':
value = int(row[3])
except:
continue
print(value)
Thank you so much!
Actually, I think that in this specific case generic exception handling may be deemed acceptable because the code is very simple, but in more complex cases I’ll undoubtedly treasure your advice.
Regards,
Alessia
After all, since my CSV file is small, looping through all the rows is a computationally sustainable solution, but I’ll certainly keep in mind your advice in case I need to extract data in a more targeted way. Thank you so much!
Alessia