第六章:文件系统-codecs:字符串编码和解码-处理文件

6.10.2 处理文件
处理I/O操作时,编码和解码字符串尤其重要。不论是写至一个文件、套接字还是其他流,数据都必须使用适当的编码。一般来讲,所有文本数据在读取时都需要由其字节表示解码,写数据时则需要从内部值编码为一种特定的表示。程序可以显式地编码和解码数据,不过取决于所用的编码,要想确定是否已经读取足够的字节来充分解码数据,这可能并不容易。codecs提供了一些类来管理数据编码和解码,所以应用不再需要做这个工作。
codecs提供的最简单的接口可以替代内置open()函数。这个新版本的函数与内置函数的做法很相似,不过增加了两个参数来指定编码和所需的错误处理技术。

from codecs_to_hex import to_hex

import codecs
import sys

encoding = sys.argv[1]
filename = encoding + '.txt'
print('Writing to',filename)
with codecs.open(filename,mode='w',encoding=encoding) as f:
    f.write('francais')

# Determine the byte grouping to use for to_hex().
nbytes = {
    'utf-8':1,
    'utf-16':2,
    'utf-32':34
    }.get(encoding,1)

# Show the raw bytes in the file.
print('File contents:')
with open(filename,mode='rb') as f:
    print(to_hex(f.read(),nbytes))

这个例子首先处理一个包含c的unicode串,使用命令行上指定的编码键这个文本保存到一个文件。
运行结果:
在这里插入图片描述
在这里插入图片描述
用open()读数据很简单,但有一点要注意:必须提前指定编码才能正确地建立解码器。尽管有些数据格式(如XML)会在文件中指定编码,但是通常都要由应用来管理。codecs只是取一个编码参数,并假设这个编码是正确的。

import codecs
import sys

encoding = sys.argv[1]
filename = encoding + '.txt'

print('Reading from',filename)
with codecs.open(filename,mode='r',encoding=encoding) as f:
    print(repr(f.read()))

这个例子读取上一个程序创建的文件,并把得到的unicode对象的表示打印到控制台。
运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/88670609
今日推荐