python: py2下 中文 的 文件读写 及 打印

  读写中文文件时,不需要考虑编码的情况。此时虽然可以正常从文件中读取中文,也可以正常地将中文写入文件中,但是无法正常打印中文字段到屏幕上:

# coding=utf-8

SRC_PATH = './src.txt'
DST_PATH = './dst.txt'

src_file = open(SRC_PATH, 'r')
dst_file = open(DST_PATH, 'w')
for line in src_file.readlines():
    dst_file.writelines(line)
    print line
src_file.close()
dst_file.close()
琛��夸腑蹇�����浜���

����涓�蹇��ㄤ�娴枫��

Hello world! Hello python!


  打印中文字段时,需要提前把系统编码由 ascii 转换到 utf-8

# coding=utf-8

SRC_PATH = './src.txt'
DST_PATH = './dst.txt'

import sys                       # new added
reload(sys)                      # new added
sys.setdefaultencoding('utf-8')  # new added

src_file = open(SRC_PATH, 'r')
dst_file = open(DST_PATH, 'w')
for line in src_file.readlines():
    dst_file.writelines(line)
    print line.encode('gb18030') # new added
src_file.close()
dst_file.close()
行政中心是北京。

金融中心在上海。

Hello world! Hello python!


  查看系统编码的具体转换状况:

# coding=utf-8

import sys
print ('origin_encoding = {}'.format(sys.getdefaultencoding()))
reload(sys)
sys.setdefaultencoding('utf-8')
print ('new_encoding = {}\n'.format(sys.getdefaultencoding()))
origin_encoding = ascii
new_encoding = utf-8


  在不转换系统编码下直接输出中文字段:

print u'中文'
print u'中文'.encode('gbk')
print u'中文'.encode('gb18030')
print
print '中文'
print u'中文'.encode('utf-8')
中文
中文
中文

涓���
涓���


  在转换系统编码下直接输出中文字段:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u'中文'
print '中文'.encode('gbk')
print '中文'.encode('gb18030')
print u'中文'.encode('gbk')
print u'中文'.encode('gb18030')
print
print '中文'
print '中文'.encode('utf-8')
print u'中文'.encode('utf-8')
中文
中文
中文
中文
中文

涓���
涓���
涓���


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值