Python中读取txt文本出现“ 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence”的解决办法
文件读取与写入:
1.读取
tf = open("D:\月_子_疏\Python--2021\Pyword.txt",encoding='utf-8') print(tf.readline()) tf.close() # 中国是个伟大的国家 tf = open("D:\月_子_疏\Python--2021\Pyword.txt","rb") print(tf.readline()) tf.close() # b'xe4xb8xadxe5x9bxbdxe6x98xafxe4xb8xaaxe4xbcx9fxe5xa4xa7xe7x9ax84xe5x9bxbdxe5xaexb6'
file = open("D:\月_子_疏\Python--2021\Pyword.txt",encoding = "utf-8") print(file.read(2)) # 读取前 size 个字符,如果无参,全部读取并以字符串形式 read(size = -1) print(file.readline(7)) # 读取前size行,无参,读取一行 readline(size = -1) print(file.readlines()) # 读取全部,如果有参数,读取前hint行,均产生列表形式 readlines(hint = -1) file.close() ''' 中国 是个伟大的国家 [' ', '武汉是个英雄的城市'] '''
file = open("D:\月_子_疏\Python--2021\Pyword.txt",encoding = "utf-8") for line in file : print(line) file.close() ''' 中国是个伟大的国家 武汉是个英雄的城市 '''
2.写入
file = open("D:\月_子_疏\Python--2021\Pyword.txt",'w+') temp = "我是分隔符 " ls = ["伟大的国家是中国","----","英雄的城市是武汉"] file.write(temp) file.writelines(ls) file.seek(0) for line in file : print(line) file.close() ''' 我是分隔符 伟大的国家是中国----英雄的城市是武汉 '''
自动轨迹绘制:
import turtle as t t.title("自动轨迹绘制") t.setup(800,600,0,0) t.pencolor("red") t.pensize(5) datals = [] file = open("D:\月_子_疏\Python--2021\data.txt") for line in file : line = line.replace(" ","") datals.append( list( map( eval,line.split(",") ) ) ) file.close() for i in range(len(datals)) : t.pencolor(datals[i][3],datals[i][4],datals[i][5]) t.fd(datals[i][0]) if datals[i][1] : t.right(datals[i][2]) else : t.left(datals[i][2]) t.done() ''' map() 会根据提供的函数对指定序列做映射。 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。 data.txt 300,0,144,1,0,0 300,0,144,0,1,0 300,0,144,0,0,1 300,0,144,1,1,0 300,0,108,0,1,1 184,0,72,1,0,1 184,0,72,0,0,0 184,0,72,0,0,0 184,0,72,0,0,0 184,1,72,1,0,1 184,1,72,0,0,0 184,1,72,0,0,0 184,1,72,0,0,0 184,1,72,0,0,0 184,1,720,0,0,0 '''
一、二维数据:
worldcloud:
2021-03-10