Advertisement
steve-shambles-2109

Base64 encode and decode a file

Feb 29th, 2020
1,050
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. """Code snippets vol-44-snip-216
  2. Base64 encode and decode a file.
  3.  
  4. By Steve Shambles
  5. Feb 2020
  6. stevepython.wordpress.com
  7.  
  8. Download all snippets so far:
  9. https://wp.me/Pa5TU8-1yg
  10.  
  11. Requirements:
  12. A text file called test.txt in current directory.
  13. Base64 is part of the standard library.
  14. """
  15. import base64
  16.  
  17. with open('test.txt', 'rb') as f:
  18.     encoded_str = base64.b64encode(f.read())
  19.  
  20. print('-' *79)
  21. print('test.txt file encoded as:')
  22. print('-' *79)
  23. print(encoded_str)
  24. print('-' *79)
  25.  
  26. with open('test-enc64.txt', 'wb') as f:
  27.     f.write(encoded_str)
  28.  
  29. with open('test-enc64.txt', 'rb') as f:
  30.     decoded_str = base64.b64decode(f.read())
  31. print('test.txt file decoded back again:')
  32. print('-' *79)
  33. print(decoded_str)
  34.  
  35. with open('test-decoded.txt', 'wb') as f:
  36.     f.write(decoded_str)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement