gamelife521 发表于 2020-5-13 22:43:01

课后作业33讲最后一题

把文件关闭放在 finally 语句块中执行还是会出现问题,像下边这个代码,当前文件夹中并不存在"My_File.txt"这个文件,那么程序执行起来会发生什么事情呢?你有办法解决这个问题吗?>;
try:
    f = open('My_File.txt') # 当前文件夹中并不存在"My_File.txt"这个文件T_T
    print(f.read())
except OSError as reason:
    print('出错啦:' + str(reason))
finally:
    if 'f' in locals(): # 如果文件对象变量存在当前局部变量符号表的话,说明打开成功
      f.close()
答案这里的if ‘f’ in locals(),这个locals()是一个什么函数,有什么用,这里的‘f’ 是指代 f = open('My_File.txt') 这里的f在内存中占的内容吗,能举例详说一下locals()用法吗

永恒的蓝色梦想 发表于 2020-5-13 22:53:14

locals() 如果在函数中调用则为局部变量字典,否则为全局变量字典>>> f
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
    f
NameError: name 'f' is not defined
>>> locals()['f']=0
>>> f
0>>> f=str()
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'f': ''}
>>> del f #等价于 del locals()['f']
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}>>> a=0
>>> b=True
>>> c=()
>>> d='Hi'
>>> a
0
>>> b
True
>>> c
()
>>> d
'Hi'
>>> locals().clear()
>>> a
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>> b
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
    b
NameError: name 'b' is not defined
>>> c
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
    c
NameError: name 'c' is not defined
>>> d
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
    d
NameError: name 'd' is not defined

沐羽尘 发表于 2020-5-13 23:00:15

楼上大佬的样子{:9_232:}
页: [1]
查看完整版本: 课后作业33讲最后一题