程式語言 - Python - 解決Strings must be encoded before hashing問題



參考資訊:
https://stackoverflow.com/questions/7585307/how-to-correct-typeerror-unicode-objects-must-be-encoded-before-hashing

問題如下:

Traceback (most recent call last):
  File "/home/steward/Downloads/run.py", line 8, in 
    print('{}'.format(get_sha1(sys.argv[1])))
                      ^^^^^^^^^^^^^^^^^^^^^
  File "/home/steward/Downloads/run.py", line 6, in get_sha1
    return hashlib.sha1(f.read()).hexdigest()
           ^^^^^^^^^^^^^^^^^^^^^^
TypeError: Strings must be encoded before hashing

解法如下:

return hashlib.sha1(f.read().encode('utf-8')).hexdigest()