Diagram: Conversion Between Str and Bytes Conversion to String
|
def to_str(bytes_or_str): if isinstance(bytes_or_str, bytes): # bytes_or_str is bytes. value = bytes_or_str.decode('utf-8') else: # bytes_or_str is not bytes, but str. value = bytes_or_str return value |
|
>>> bytes_ex = b'This is a string.' >>> str_ex = 'This is a string' >>> to_str(bytes_ex) 'This is a string' >>> to_str(str_ex) 'This is a string' |
Conversion To Bytes
|
def to_bytes(bytes_or_str): if isinstance(bytes_or_str, str): # bytes_or_str is str. value = bytes_or_str.encode('utf-8') else: # bytes_or_str is not str, but bytes value = bytes_or_str return value |
|
>>> bytes_ex = b'This is a string.' >>> str_ex = 'This is a string' >>> to_bytes(bytes_ex) b'This is a string' >>> to_bytes(str_ex) b'This is a string' |
Write a?File in Write Binary Mode (‘wb’)
|
with open('binary.txt', 'wb') as f: f.write(to_bytes(str_ex)) with open('bytes.txt', 'wb') as f: f.write(to_bytes(bytes_ex)) |
Write a?File in Write Character?Mode (‘w’)
|
with open('str.txt', 'w') as f: f.write(to_str(str_ex)) with open('str.txt', 'w') as f: f.write(to_str(bytes_ex)) |