Python初试云雨情

本文介绍了从Python 2到Python 3中文件操作的变化,解释了如何将file()替换为open()来避免NameError,并展示了如何使用with语句正确地打开和关闭文件。
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')

转载于:https://www.cnblogs.com/dreamfine/p/7501223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值