as的意思不是为文件重命名吗,难道在这里有什么特殊的意义?
打印下他们的类型,发现类型不一致。
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')
2 回答5.1k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
as 不是重命名原文件。
as 是代表打开后的文件句柄。比如
f = open(file_1,'w')
,as 后面那个相当于这个 f 变量。之所以用with是因为with是一个上下文管理器,可以自动关闭文件。不需要主动去调用f.close().