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?