7872人加入学习
(35人评价)
Python零基础入门学习2020最新版(SiKi)

使用Python3.8 于2019/10/20开始录制

价格 免费

读取中文txt文件时,经常会出现: ‘gbk’ codec can’t decode bytes in position 31023: illegal multibyte sequence。
主要讲一种情况就是文章中含有utf-8或gbk无法编码的字符情况。

原因是含有无法编码的字符,或者是打开的编码不对。
解决方法一:用 utf-8 编码打开 (实际文件的编码方式)
如下: open('d:/data/synopses_list_wiki.txt',encoding='utf-8')

解决方法二:在open中加入errors=‘ignore’ ,忽略它即可
如下:

open('d:/data/synopses_list_wiki.txt',errors='ignore')

[展开全文]

读取整个文件:

with open('game.txt') as file:
    content = file.read()

    print(content)

 

读每一行:

with open('game.txt') as file:
    for line in file:
        print(line)

[展开全文]