python学习之路:文件with自动关闭+字符转码
Posted Py小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之路:文件with自动关闭+字符转码相关的知识,希望对你有一定的参考价值。
with语句可实现文件的自动关闭功能:
1 import sys 2 \'\'\' 3 with open("yesterday2","r",encoding="utf-8") as f: #自动关闭并释放文件资源 4 for line in f: 5 print(line) 6 \'\'\' 7 with open("yesterday2","r",encoding="utf-8") as f,\\ 8 open("yesterday2","r",encoding="utf-8") as f2: 9 for line in f: 10 print(line)
字符转码:https://www.cnblogs.com/jxzheng/p/5186490.html
https://www.cnblogs.com/nulige/p/6063999.html
1 s ="你好" #默认Unicode 2 s_to_GBK =s.encode("GBK") #Unicode转码成gbk 3 print(s_to_GBK) 4 5 print(s_to_GBK.decode("GBK")) #从GBK转码成unicode 6 7 print(s.encode("GBK")) 8 print(s.encode("utf-8")) 9 print(s.encode("utf-8").decode("utf-8").encode("gb2312")) 10 11 import sys 12 print(sys.getdefaultencoding()) #取系统默认encoding
以上是关于python学习之路:文件with自动关闭+字符转码的主要内容,如果未能解决你的问题,请参考以下文章