Search code examples
pythonunicode

Error reading a .txt file with np.loadtxt python


I'm trying to read a .txt file but I got this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

this is my code.

import numpy as np
data=np.loadtxt('Data.txt')
print(data)

how could I fix it?


Solution

  • probably your file was encoded in utf-16 format that's why you're seeing a Unicode error! can you try this out:

    import numpy as np
    data=np.loadtxt('data.txt', encoding='utf-16')
    print(data)
    

    As you didn't mention file content, can you confirm if it's worked or what type of new error you're seeing?

    • Read the comment made by Mark Tolonen for better explanation about the error