Python中讀取檔案亂碼

2021-09-27 10:26:37 字數 336 閱讀 5646

python中讀取目標檔案後,控制台出現亂碼,

解決方案:

file_path=r』f:\wechat\wechat files\filename.txt』

with open(file_path,『rb+』) as file_object:

contents=file_object.read()

print contents.rstrip().decode(『gbk』).encode(『utf-8』)

要對檔案進行deconde和encode,在open()內要加上『rb+』。

同時要注意的是找絕對路徑時,要在路徑的第乙個單引號前面加r,且路徑中要用.

python讀取檔案亂碼

方法一 使用codecsimportcodecsf codecs.open nlpir readme.txt r gbk line f.readline whileline printline,line f.readline f.close 上面的方法很慢,可以直接讀取整個檔案codecs.open...

python 讀取檔案亂碼問題

一 問題 python讀取檔案時會遇到亂碼的問題 二 解決方法 1 已utf 8格式開啟文件 f open r e python liaotian.txt r encoding utf 8 f.seek 0,0 for each line in f print each line f.close 2...

python讀取檔案亂碼問題

今天突然想做乙個實時讀取 日誌檔案的程式,然後用python爬蟲直接爬取檔案,用唯讀的方式開啟避免對 系統 寫入日誌 造成影響。上 usr bin env python coding utf 8 import subprocess import time import chardet p 0 wit...