看板 Python 關於我們 聯絡資訊
我的資料夾下有一堆純文字檔案 但是它們有些是big5,有些是UTF-8 我想用os.walk去逐一讀取它們,類似這樣 判斷每一行裡是不是包含我指定的keyword: def search(directory, keyword): for (a, _, filenames) in walk(directory): for f in filenames: file = open(a + "\\" + f, "r", encoding='UTF-8') lines = file.readlines() for l in lines: if keyword in l: # do something 問題是以上程式碼對於UTF-8編碼的檔案都沒問題 但如果是遇到混雜的BIG5就會錯誤 我想請問,這種混雜編碼的情況,要怎麼處理會比較好呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.217.181.63 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1549987954.A.F20.html
djshen: 用rb開, decode utf8, 有error就decode big5? 02/13 01:16
lajji: Try except 02/13 11:21
cspy: error='replace' 02/18 01:43