-3
import sys

script, error = sys.argv


def main(language_file, errors):
    line = language_file.readline()

    if line:
        print_line(line, errors)
        return main(language_file, errors)


def print_line(line, errors):
    raw_bytes = line.strip()
    cooked_string = raw_bytes.decode(errors=errors)
    print(raw_bytes, "<===>", cooked_string)


languages = open("languages2.txt")

main(languages, error)

If I run this I get 'str' object has no attribute 'decode'.

The languages2.txt file only contains bytes which I want to decode.

If I try raw_bytes.encode(errors=errors) the program runs but obviously prints out only the bytes 2 times.

I'm new to this, so sorry for the dumb question.

Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
Adrian
  • 1
  • 1
  • 2
    Are you saying that languages2.txt is a binary file? – DarkKnight Dec 19 '21 at 13:59
  • What you call `raw_bytes` is simply not really raw bytes... It's just a string (as the error suggests). If you want to read bytes, you need to open the file in binary mode... – Tomerikoo Dec 19 '21 at 14:01
  • Does this answer your question? [Reading a binary file with python](https://stackoverflow.com/q/8710456/6045800) – Tomerikoo Dec 19 '21 at 14:02
  • By convention, if the file is a .txt file, it is readable with Linux `cat` or Windows notepad. It is not binary. – rajah9 Dec 19 '21 at 14:06
  • Now I tried to open the file like this: `languages = open("languages2.txt", "rb")` . But i get the same output as with `raw_bytes.encode(errors=errors)` – Adrian Dec 19 '21 at 14:13
  • Now you get a binary object and try to encode that. Either you have a string that you want to encode or a binary object you want to decode. If you have a text file then why don't you open the file in text mode and print the line without trying to encode it? You might want to specify the encoding of the file in the call to `open`. – Matthias Dec 19 '21 at 14:15

1 Answers1

0

By default, the file object will decode the bytes read (i.e. text mode). If you want to do the decoding yourself you have to open the file in binary mode.