opening a text file on a Macbook

Viewed 79

I downloaded a text file on my Macbook, I believe my code is correct and there are no errors in the spelling of the file. This is my code

Mydata=r'/Users/janetnorio/Desktop/CylindricalRollerBearingData_01.txt'
with open(Mydata, 'r') as Datafile:
  Datafile.readline()
  Datafile.readline()
  Units=Datafile.readline().split('\t')

and the code prints the following

    Traceback (most recent call last):
      File "/Applications/Python 3.7/Homework assignments and other /Python_project01.py", line 7, in <module>
        Datafile.readline()
      File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py", line 322, in decode
        (result, consumed) = self._buffer_decode(data, self.errors, final)
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 24: invalid continuation byte

Can someone tell me what is wrong?

3 Answers

There is likely an incorrect usage of the unicode characters inside the file as according to wikipedia, there is info about how certain binary values have to followed by other values Here: https://en.wikipedia.org/wiki/UTF-8#Design. I cannot say this for sure, however because I did not get to see the contents of the text file.

Mydata=r'/Users/janetnorio/Desktop/CylindricalRollerBearingData_01.txt'
with open(Mydata, 'r', encoding="ISO-8859-1") as Datafile:
  Datafile.readline()
  Datafile.readline()
  Units=Datafile.readline().split('\t')

I think you should add an encoding argument for open.

Currently, can't test the code below in MacOS environment,
but summarizing everyone's answers and comments, your code should look like

import chardet

my_data_filepath = '<my_filepath>'

with open(my_data_filepath, 'rb') as file:
  my_data_encoding = chardet.detect(file.read())['encoding']

if my_data_encoding:
  with open(my_data_filepath, encoding=my_data_encoding) as file:
    file.readline()
    file.readline()
    units = file.readline().split('\t')
else:
  print(f'Encoding is not recognized.')
Related