Python における `'NoneType' object has no attribute '__getitem__'` というエラーについて


画像のエラーはいったいどうすれば解決できるのでしょうか？  
調べた結果属性に問題があるようですがよくわからなかったため質問しました。

ソースコードは以下に記載します。

よろしくお願いします。

[code]

    import sys, getopt
    import sqlite3
    
    class Location:
    
        def __init__(self, filename=""):
            self.filename = filename
            self.locations = list()
    
        def seek(self):
            if self.filename=="":
                return False
    
            file = open(self.filename,"r")
    
            for line in file:
                line_sep=line.split("\t")
                if( len(line_sep) > 2 ):
                    if(line_sep[1] == "LOC"):
                       time     = line_sep[2].split(',')[0]
                       latitude = line_sep[2].split(',')[1]
                       longitude= line_sep[2].split(',')[2]
    
                       location = {'time':time, 'latitude':latitude, 'longitude':longitude}
                       self.locations.append(location)
            return True
    
        def printAll(self):
            if(len(self.locations) > 0):
                print 'time, latitude, longitude'
            for location in self.locations:
                print location['time'], location['latitude'], location['longitude']  
    
    class Audio:
    
        def __init__(self, filename=""):
            self.filename = filename
            self.startTime = 0.0
            self.stopTime = 0.0
    
        def seek(self):
            if self.filename=="":
                return False
    
            file = open(self.filename,"r")
    
            for line in file:
                line_sep=line.split()
                if( len(line_sep) > 2 ):
                    if(line_sep[1] == "AUDIO"):
                        if(line_sep[2] == "start"):
                            self.startTime = line_sep[0]
                        elif(line_sep[2] == "stop"):
                            self.stopTime = line_sep[0]
    
            return True
    
        def printTime(self):
            print self.startTime, self.stopTime
    
        def getDuration(self):
            return (float(self.stopTime) - float(self.startTime))
    
    
    class FileManager:
        def __init__(self, filename, database):
            #database connection
            self.conn = sqlite3.connect(database)
            self.cur = self.conn.cursor()
            self.filename = filename
    
            # filename must be separated by '-'. (e.g. hasc-20120527-115511-raw.log)
            self.idname = '-'.join(filename.split("-")[0:3])
    
        def _getFileinfoId(self):
            self.cur.execute("select fileinfo.id from files inner join fileinfo on files.id=fileinfo.fileId where files.filename like '" + self.idname + "%'")
            return self.cur.fetchone()[0]
    
        def updateDatabase(self):
            fileinfoId = str(self._getFileinfoId())
            audio = Audio(self.filename)
            audio.seek()
    
            self.cur.execute("update fileinfo set startTime='"+ audio.startTime + "' where id=" + fileinfoId )
            self.cur.execute("update fileinfo set endTime='"  + audio.stopTime  + "' where id=" + fileinfoId )
            self.conn.commit()
    
            loc = Location(filename = self.filename)
            loc.seek()
            for location in loc.locations:
                self.cur.execute("insert into geolocations(fileId, time, latitude, longitude) values("+ fileinfoId +", "+ location['time'] +", "+ location['latitude'] +", "+ location['longitude']+")")
                self.conn.commit()
    
    def main(argv):
        logfile = ''
        database = ''
        try:
            opts, args = getopt.getopt(argv,"hl:d:",["log=","db="])
            if len(opts) < 1:
                raise getopt.GetoptError("")
        except getopt.GetoptError:
            print 'hascseeker.py --log <logfile> --db <databasefile>'
            sys.exit()
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print 'hascseeker.py --log <logfile> --db <databasefile>'
                sys.exit()
            elif opt in ("-l", "--log"):
                logfile = arg
            elif opt in ("-d", "--db"):
                database = arg
    
        man = FileManager(logfile, database)
        man.updateDatabase()
    
    if __name__ == "__main__":
       main(sys.argv[1:])
    
[/code]

![エラー画面](https://i.stack.imgur.com/TsVX9.jpg)




SQL 文の実行結果が 0 件の場合、`fetchone()` は `None` を返します。

[11.13. sqlite3 — DB-API 2.0 interface for SQLite
databases](https://docs.python.org/2.7/library/sqlite3.html#sqlite3.Cursor.fetchone)

> Cursor.fetchone()
>
> Fetches the next row of a query result set, returning a single sequence, or
> None when no more data is available.

なので、以下の様に書くべきではないでしょうか。

[code]

    def _getFileinfoId(self):
      self.cur.execute("select fileinfo.id from files inner join fileinfo on files.id=fileinfo.fileId where files.filename like '" + self.idname + "%'")
      result = self.cur.fetchone()
      return ( None if result is None else result[0] )
    
[/code]

ただ、`None` の場合にはそのまま返していますので、適宜変更して下さい。

