Ex23 Study Drill 3: Found two solutions, but is one of them better?

I did exercise 23 today and loved it because it felt like something clicked in my head when I came to understand how that loop works. I then tried to work out study drill 3 and found two solutions. Now I’m wondering if one of them is better than the other and if so, why?

Here is solution 1:

import sys
script, input_encoding, error = sys.argv

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

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

def print_line(line, encoding, errors):
    next_lang = line.strip()
    raw_bytes = next_lang.decode(encoding, errors=errors)
    cooked_string = raw_bytes.encode(encoding, errors=errors)

    print(raw_bytes, "<===>", cooked_string)

languages = open("languages.txt", encoding="utf-8")

main(languages, input_encoding, error)

I simply encode the line while its read and switched the encode and decode in the print_line function.

And solution 2:

import sys
script, input_encoding, error = sys.argv

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

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

def print_line(line, encoding, errors):
    next_lang = line.strip()
    raw_bytes = next_lang.decode(encoding, errors=errors)
    cooked_string = raw_bytes.encode(encoding, errors=errors)

    print(raw_bytes, "<===>", cooked_string)

languages = open("languages.txt", 'r+b')

main(languages, input_encoding, error)

Here I just read the languages.txt in byte-mode and also switched the decoding/encoding in the print_line function.

So is one of those solutions better than the other one? Or are both solutions “bad” in some way?

Oh, and one more question I had while doing ex23.

Shouldn’t we add

languages.close()

at the end? Why isn’t that needed here?

I guess both solutions are viable.

And yes, you should close the file. It’s not a problem here because Python does it automatically on exit, but you may run into situations where you iterate over huge numbers of files. Then you should definitely close them because the number of files an application can open at the same time is normally limited by the OS.

1 Like