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,
If you ‘know’ where the element is (in this case row 6, column 3: rows and columns start at zero), then this will do it:
with open('cards.csv') as cards:
csv_reader = csv.reader(cards)
for index, row in enumerate(csv_reader):
if index == 6:
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.
with open('cards.csv') as file_obj:
reader_obj = csv.reader(file_obj)
for row in reader_obj:
if row == 'Diamond':
value = int(row)
Don’t use a “bare except”:
# Bad idea!
because it catches all exceptions, including ones that might be due to bugs in your program, e.g.
NameError because you misspelled a name.
Catch only specific exception(s) that you want to handle, such as
IndexError in this instance.
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.
This pattern can be sped using pandas without iterating over the whole .csv file, using .loc:
df.loc[df["row_1"] == "Diamond", "row_4"].values[-1]
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!