在python中使用 with open,为什么一定要加后缀as?

as的意思不是为文件重命名吗,难道在这里有什么特殊的意义?

加入as,执行成功

没有as,执行失败

阅读 8.2k
3 个回答

as 不是重命名原文件。
as 是代表打开后的文件句柄。比如 f = open(file_1,'w'),as 后面那个相当于这个 f 变量。之所以用with是因为with是一个上下文管理器,可以自动关闭文件。不需要主动去调用f.close().

打印下他们的类型,发现类型不一致。

In [5]: import json 
In [6]: num = [1,2,3,4,5,6,7]
In [7]: file_1 = 'first.json'
In [8]: with open(file_1,'w') as joe:
   ...:     print(type(joe))
   ...:     json.dump(num, joe)
   ...:     
<class '_io.TextIOWrapper'>
In [14]: import json 
In [15]: num = [1,2,3,4,5,6,7]
In [16]: file_1 = 'first.json'
In [17]: with open(file_1, 'w'):
    ...:     print(type(file_1))
    ...:     json.dump(num, file_1)
    ...:     
    ...:     
    ...:     
<class 'str'>
AttributeError: 'str' object has no attribute 'write'

第二段代码
虽然使用了open方法打开文件,但是还是用了直接字符串对象file_1,相当于没有open这一步骤。
等价于以下代码:

import json
file_1 = 'first.json'
json.dump(num, file_1)

而字符串本身是没有写入这个方法的,因此报错:AttributeError: 'str' object has no attribute 'write'

不想要with 可以讲打开的对象赋值给f = open(file_1,'w')

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题