0

I want to read the last 24 rows of a csv file using python. So for example if the csv Data has 500 rows, I want to write row 476 to row 500. I dont know how many rows the csv file has. I tried this code, doesn't work. Can someone help me?

z=0 
r=0

for row in csvData:  
    z += 1      

for row in csvData:  

    if r > (z-30) || r < z:    
        html.write('{ x: new Date('+ row[0] + '), y:' + row[2] + '},')   
    r += 1

1 Answers1

1

The reason why your code doesn't work is that csvData has been read completely in the first for loop.

You'd need to "rewind" the file with csvData.seek(0) between the two loops. See "Why can't I call read() twice on an open file?"

There's a shorter way though, you could load all the lines as a list with readlines(), and select the last 24 lines directly:

for row in csvData.readlines()[-24:]:
    # do something with row

This should work fine as long as your csvData isn't huge.

If you need a more efficient (but longer) method, you could use the answer to "Get last n lines of a file with Python, similar to tail".

Community
  • 1
  • 1
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124