首页 > 编程语言 > 详细

python学习之路:文件with自动关闭+字符转码

时间:2017-11-13 22:23:18      阅读:291      评论:0      收藏:0      [点我收藏+]

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自动关闭+字符转码

原文:http://www.cnblogs.com/xiaobai005/p/7828419.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!