day2--补充与总结

一 有一种情况,在Windows系统上面有一个文件,编码为gbk,将其上传到Linux虚拟机,系统编码为utf-8,

使用cat命令查看时是乱码,这时如何解决?

[root@localhost ~]# cat x.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

with open('hhh.txt',mode='r') as f1:
  content=f1.read()
  #content1=content.decode('gbk')#(u'\u4f60\u597d', <type 'unicode'>)
  #content1=content.decode('gbk').encode('utf-8')#('\xe4\xbd\xa0\xe5\xa5\xbd', <type 'str'>)
  content1=content.decode('gbk').encode('utf-8')
  print(content1)
  print(type(content1))
##结果为:   #这个我认为首选
#你好
#<type 'str'>
'''
with open('hhh.txt','rb') as f1:
  content=f1.read()
  content1=content.decode('gbk')
  print(content1)
  print(type(content1))
###结果为
#你好
#<type 'unicode'>
'''

如果想要使用cat命名查看而不报错呢

[root@localhost ~]# cat xx.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
with open('hhh.txt',mode='r') as f1,\
  open('hhh.bak',mode='w') as f2:
  content=f1.read().decode('gbk').encode('utf-8')
  f2.write(content)
os.remove('hhh.txt')
os.rename('hhh.bak','hhh.txt')

猜你喜欢

转载自www.cnblogs.com/mmyy-blog/p/9118371.html
今日推荐