Python TypeError: 'NoneType' 对象不可下标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27718385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: 'NoneType' object is not subscriptable
提问by Abby Cordovilla
The error: names = curfetchone()[0]
错误: names = curfetchone()[0]
TypeError: 'NoneType' object is not subscriptable.
I tried checking the indentation but still there's an error. I read that maybe the variable names returns 'None' if there is no record of the filename in the database.
我尝试检查缩进,但仍然有错误。我读到如果数据库中没有文件名的记录,变量名可能会返回“无”。
I use the same variable 'names' in other 'def' and it works fine. I'm sure it has to do with the 'None' value being returned.
我在其他“def”中使用了相同的变量“names”,它工作正常。我确定这与返回的“无”值有关。
global filename
global t
try:
con = sqlite3.connect('textdb.db')
cur = con.cursor()
filename = tkinter.simpledialog.askstring("Open file...", "Input filename to open:")
if filename != None:
cur.execute("SELECT file_name FROM file_info WHERE file_name = ?", (filename,))
names = cur.fetchone()[0]
same = str(names)
if filename == same:
cur.execute("SELECT file_content FROM file_info WHERE file_name = ?", (filename,))
content = cur.fetchone()[0]
t = str(content)
text.delete(0.0, END)
text.insert(0.0, t)
else:
result = tkinter.messagebox.askyesno(title="File doesn't exist", message="'"+(filename)+"' doesn't exist. Make a new file using '"+(filename)+"'?")
if result == True:
cur.execute("SELECT COUNT(*) FROM file_info")
count_row = cur.fetchone()
cntdata = count_row[0]
incr = (cntdata + 1)
t = str(text.get(0.0, END))
curtime = str(ctime())
cur.execute("INSERT OR IGNORE INTO file_info VALUES(?, ?, ?, ?, ?)", (incr, filename, t, curtime, curtime,))
con.commit()
except sqlite3.Error:
if con:
con.rollback()
finally:
if con:
con.close()
回答by glglgl
If, due to whatever reason (empty result set?) curfetchone()
returns None
, a [0]
access is of course forbidden (as the error message clearly says).
如果由于某种原因(空结果集?)curfetchone()
返回None
,则[0]
访问当然是被禁止的(正如错误消息明确说明的那样)。
So better do that in two steps and do
所以最好分两步做
row = curfetchone()
if row is not None:
names = row[0]
# proceed
else:
# act appropriately