开发者社区> 问答> 正文

读写文本数据

你需要读写各种不同编码的文本数据,比如ASCII,UTF-8或UTF-16编码等。

展开
收起
哦哦喔 2020-04-17 12:21:03 972 0
1 条回答
写回答
取消 提交回答
  • 使用带有 rt 模式的 open() 函数读取文本文件。如下所示:
    
    # Read the entire file as a single string
    with open('somefile.txt', 'rt') as f:
        data = f.read()
    
    # Iterate over the lines of the file
    with open('somefile.txt', 'rt') as f:
        for line in f:
            # process line
            ...
    类似的,为了写入一个文本文件,使用带有 wt 模式的 open() 函数, 如果之前文件内容存在则清除并覆盖掉。如下所示:
    
    # Write chunks of text data
    with open('somefile.txt', 'wt') as f:
        f.write(text1)
        f.write(text2)
        ...
    
    # Redirected print statement
    with open('somefile.txt', 'wt') as f:
        print(line1, file=f)
        print(line2, file=f)
        ...
    如果是在已存在文件中添加内容,使用模式为 at 的 open() 函数。
    
    文件的读写操作默认使用系统编码,可以通过调用 sys.getdefaultencoding() 来得到。 在大多数机器上面都是utf-8编码。如果你已经知道你要读写的文本是其他编码方式, 那么可以通过传递一个可选的 encoding 参数给open()函数。如下所示:
    
    with open('somefile.txt', 'rt', encoding='latin-1') as f:
        ...
    Python支持非常多的文本编码。几个常见的编码是ascii, latin-1, utf-8和utf-16。 在web应用程序中通常都使用的是UTF-8。 ascii对应从U+0000到U+007F范围内的7位字符。 latin-1是字节0-255到U+0000至U+00FF范围内Unicode字符的直接映射。 当读取一个未知编码的文本时使用latin-1编码永远不会产生解码错误。 使用latin-1编码读取一个文件的时候也许不能产生完全正确的文本解码数据, 但是它也能从中提取出足够多的有用数据。同时,如果你之后将数据回写回去,原先的数据还是会保留的。
    
    2020-04-17 12:21:40
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载