fd = file(filename, "r",encoding='utf-8')
上句运行出现错误:NameError: name 'file' is not defined
解决办法:file()改为open(),python 3.0 不再支持file
file
2to3 fixer ☐ six support ☐
In Python 2 there is a file type builtin. This is replaced with various file types in Python 3. You commonly see code in Python 2 that uses file(pathname)which will fail in Python 3.
Replace this usage with open(pathname).If you need to test for types you can in Python 3 check for io.IOBase instead of file.
IOBase是一个上下文管理器,所以也支持with语句。在这个例子中,文件在with语句块执行完成后被关闭,即使错误发生也会关闭文件。
with open('spam.txt', 'w') as file:
file.write('spam and eggs')