码迷,mamicode.com
首页 > 编程语言 > 详细

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

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

标签:文件   efault   xzhe   sys   文件的   bsp   logs   encode   unicode   

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

标签:文件   efault   xzhe   sys   文件的   bsp   logs   encode   unicode   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!