2022年 11月 5日

python怎么读取中文文件-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 = {} ‘.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’)中文

中文

中文

中文

中文

涓���

涓���

涓���