Python - read text file with weird utf-16 format

前端 未结 4 817
走了就别回头了
走了就别回头了 2021-01-17 17:00

I\'m trying to read a text file into python, but it seems to use some very strange encoding. I try the usual:

file = open(\'data.txt\',\'r\')

lines = file.         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 17:45

    This is really just @abarnert's suggestion, but I wanted to post it as an answer since this is the simplest solution and the one that I ended up using:

        file = io.open(filename,'r',encoding='utf-16-le')
        data = np.loadtxt(file,skiprows=8)
    

    This demonstrates how you can create a file object using io.open using whatever crazy encoding your file happens to have, and then pass that file object to np.loadtxt (or np.genfromtxt) for quick-and-easy loading.

提交回复
热议问题