g = None
try:
g = open("mydata.txt", "r")
except IOError:
print(’Python could not open the file mydata.txt.’)
if g:
try:
lines = g.readlines()
print("The list of lines is:")
print(lines)
except IOError:
print(’Error while trying to read the data in the file.’)
这是一个在我的教科书中使用Python中的try
和except
的示例。该教科书声称“g
被初始绑定为None
(在if
声明的布尔上下文中被视为False
)”。根据我的理解,g
已经包含了从open
函数返回的文件对象,在if
语句的布尔上下文中它怎么会被当作False
?如何将变量分配给两个对象?
感谢您的回复。但是'g'如何在if语句中重新分配'None'?教科书说'g'在if语句的布尔上下文中被视为False。 –
@alexlau它永远不会被重新分配回来。 'try' /'catch'的目的是捕获如果打开文件无法打开的异常。如果'open'抛出异常,重新分配不会发生,所以当'try'退出时'g'仍然保持'None'。 '如果g:'基本上检查打开是否成功。 – Carcigenicate