簡體   English   中英

Python:讀取文件會出現 UnicodeDecodeError

[英]Python: Reading file gives a UnicodeDecodeError

我正在嘗試編寫一個腳本來清除數據 txt 文件中不必要的字符。 我能夠成功運行腳本一次,但每次嘗試都會給出錯誤UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 8149: invalid start byte

import codecs
import sys

if len(sys.argv) < 2:
        startFile = "test.txt"
else:
        startFile = sys.argv[1]

finishFile = "newtest.txt"



def cleanFile():
        f = open(startFile, "r")
        #f = codecs.open("GNMFDB.TXT", "r", "utf-8")
        newFile = open(finishFile, "a")

        for line in f:
                line = line.replace("=", "")

                newFile.write(line)


def clearNewFile():
        newFile = open(finishFile, "w")
        newFile.close()


if __name__ == "__main__":
        #startFile = "test.txt"
        #finishFile = "newtest.txt"
        clearNewFile()
        cleanFile()

我知道這個問題與 UTF-8 試圖轉換為字符串或類似的東西有關。 從 original.txt 文件中復制一些行並將它們放入我在 vim 中創建的單獨的.txt 文件中確實會導致腳本每次都成功運行。 我知道編解碼器可以用於這種情況,但是當我嘗試它時,它給了我類似的錯誤(因此該行被注釋掉了)。

您是否嘗試先對其進行編碼,然后在將其寫入 newFile 時對其進行解碼? 在讀取文件時,在這一行中,您首先必須在讀取行時對每一行進行編碼,然后在每一行上進行工作,然后再次使用 utf-8 對其進行解碼: for line in f: line.encode('utf-8') "your code goes here" line.decode('utf-8')你可以嘗試的另一個解決方案是將 try 和 except 塊放在 for 循環中,以檢查它是否發生在所有行或幾行中,如果它發生了在幾行中,您可能會刪除它們,希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM