简体   繁体   中英

'str' object has no attribute 'decode' Python 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM