python2和python3 with open as f写中文乱码

python3和python2的写法不一样具体如下:

python3:

with open(r’d:\ssss.txt’,‘w’,encoding=‘utf-8’) as f:

f.write(u’中文’)

python2中open方法是没有encoding这个参数的,如果像python3一样的写法会报异常:TypeError: ‘encoding’ is an invalid keyword argument for this function

python2中需要加上:

import sys
reload(sys)
sys.setdefaultencoding(‘utf-8’)
with open(r’d:\sss.txt’,‘w’) as f:
  f.write(unicode("\xEF\xBB\xBF", “utf-8”))#函数将\xEF\xBB\xBF写到文件开头,指示文件为UTF-8编码。
  f.write(u’中文’)
读取文件
with open(r’d:\aaa.txt’,‘r’) as ff:
  a= ff.read().encode(‘gbk’)#编码为gbk输出 控制台
  print a

或者还有一种写法:

import io
with io.open(path,‘w’,encoding=‘utf-8’) as f:
  f.write(unicode("\xEF\xBB\xBF", “utf-8”))#函数将\xEF\xBB\xBF写到文件开头,指示文件为UTF-8编码。
  f.write(u’这是中文’)

with open(r’d:\aaa.txt’,‘r’) as ff:
  a= unicode(ff.read(),‘utf-8’)#编码为UTF-8输出
  print a

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python的`with open`函数是用来打开文件并进行文件操作的。它的作用是在文件操作完成后自动关闭文件,无需手动调用`close()`方法。\[1\] 在Python 3中,`with open`的语法如下: ```python with open('/path/to/file', 'r') as f: print(f.read()) ``` 这个例子中,`with open`打开了一个名为`/path/to/file`的文件,并以只读模式打开。然后,通过`as`关键字将文件对象赋值给变量`f`。在`with`代码块中,我们可以对文件进行操作,比如使用`f.read()`读取文件内容。当代码块执行完毕后,`with`语句会自动关闭文件,无需手动调用`f.close()`方法。\[1\] 在Python 2中,`with open`的语法略有不同: ```python with open(r'd:\ssss.txt', 'w') as f: f.write(u'中 ...') ``` 这个例子中,`with open`打开了一个名为`d:\ssss.txt`的文件,并以入模式打开。同样,通过`as`关键字将文件对象赋值给变量`f`。在`with`代码块中,我们可以使用`f.write()`方法向文件入内容。当代码块执行完毕后,`with`语句会自动关闭文件,无需手动调用`f.close()`方法。\[2\] 总结来说,`with open`函数是Python中用来打开文件并进行文件操作的一种简洁、安全的方式。它可以自动关闭文件,避免了手动调用`close()`方法的繁琐。无论是在Python 2还是Python 3中,都可以使用`with open`函数来进行文件操作。 #### 引用[.reference_title] - *1* [文件读](https://blog.csdn.net/Alie1129/article/details/101863562)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [python with open as f中文码](https://blog.csdn.net/weixin_39914752/article/details/111435978)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值