0

I am reading a csv file in python using the following piece of code:

with open("data.csv", "r") as csvfile:
   reader = csv.reader(csvfile)
   for row in reader:
      print(row)

This reads the complete csv file, but how can I read a particular entry from the csv file?

Raza Javed
  • 65
  • 3
  • 11
  • 1
    Can you elaborate what do you mean by particular entry? – Saurav Panda Apr 10 '20 at 08:13
  • This may be of help: https://stackoverflow.com/questions/29334463/how-can-i-partially-read-a-huge-csv-file/44958125 – Jakub Sowa Apr 10 '20 at 08:17
  • @SauravPanda for example, my csv file has a table of some data, and the table has 3 rows and 3 columns. Now I want to read the value stored in the last row and last column (last entry of the table). How can I read the value stored at this particular index? – Raza Javed Apr 10 '20 at 09:39

1 Answers1

1

So Assuming your csv uses a delimiter like ",".

Lets say your CSV looks like this:

Name, age, gender
A,10,M
B,20,F
C,30,M

I would give you a very basic solution for this. this is to get the last row only.

with open("data.csv", "r") as csvfile:
    data_txt = csvfile.read().splitlines()
    print(data_txt[-1])

Suppose you want the gender of last line, then use:

with open("data.csv", "r") as csvfile:
    data_txt = csvfile.read().splitlines()
    last_row = data_txt[-1].split()
    gender = last_row[-1]
    print(gender)

You can do this for any element of the file as far as you know the position of data. For last item use -1 as slicing index.

Hope this helps

Saurav Panda
  • 558
  • 5
  • 12