user3157628
user3157628

Reputation: 29

Python list index out of range error?

I have a python script that gets the last line of a text file and splits it. Some users have been emailing me that the list index out of range error keeps popping up. here is relevant code:

if Data.closed == True:
    Data = open("Data.txt", "r")
#
lines = len(Data.readlines())
Data.close()

Data = open("Data.txt", "r")
if lines > 1:
    for x in range(0, lines):
        lastLine = Data.readline()
    #   

else:
    fatalError("ERROR:Map file has no data!!", True)            
#               
lastLineBroken = lastLine.split("|")
lstLnBrokLen = len(lastLineBroken)
lat = lastLineBroken[0]
lon = lastLineBroken[1]
Data.close()

Upvotes: 1

Views: 1704

Answers (3)

Jon Clements
Jon Clements

Reputation: 142256

To get the last line and split it via lat/lon, then try:

from collections import deque

with open('yourfile') as fin:
    last = deque(fin, 1)
    try:
        lat, lon = last[0].split('|', 3)[:2]
    except (IndexError, ValueError):
        pass # uh oh... no line, or no data in it...

If you had a really large file and didn't fancy iterating through it, then another approach (although most likely overkill by the looks of it):

import mmap

with open('yourfile') as fin:
    try:
        mm = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
        last_line = mm[mm.rfind('\n') + 1:]
        lat, lon = last_line.split('|', 3)[:2]
    except (ValueError, IndexError):
        pass # uh oh....

Upvotes: 2

Arovit
Arovit

Reputation: 3719

You can directly get the last element of the list (last line)

   lines = Data.readlines()
   if lines:
       lastLine = lines[-1]

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122169

You should probably add a check that you break the line into enough parts:

if len(lastLineBroken) >= 2:
    lat, lon = lastLineBroken[:2]

Upvotes: 0

Related Questions