赞
踩
- >>> b'Hello World'.decode() == "Hello World"
- True
- >>>
- import struct
- with open('binary_file.bin', 'wb') as file:
- data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64' # 二进制数据
- number = 42
- packed_data = struct.pack('I', number)
- file.write(data)
- file.write(packed_data)
- file.close()
-
- with open('binary_file.bin', 'rb') as file:
- data = file.read(len(data))
- packed_data = file.read()
- number = struct.unpack('I', packed_data)[0]
- print(data.decode())
- print(number)
- file.close()
-
-
-
- Hello World
- 42
- >>>
- string = "Hello, World!"
- byte_string = b"Hello, World!"
-
- print(type(string))
- print(type(byte_string))
- <class 'str'>
- <class 'bytes'>
- >>>
- number = 1200
- Bytes = 4
- byte_data = number.to_bytes(Bytes, 'big')
- with open('binary_file.bin', 'wb') as file:
- file.write(byte_data)
- with open('binary_file.bin', 'rb') as file:
- Number = file.read()
- NUMBER = int.from_bytes(Number, 'big')
- print(NUMBER)
- text_data = "Hello, World!"
- number = 12345
-
- with open('binary_file.bin', 'wb') as file:
- file.write(text_data.encode())
- file.seek(20)
- byte_data = number.to_bytes(4, 'big')
- file.write(byte_data)
-
- with open('binary_file.bin', 'rb') as file:
- text = file.read(10)
- print(text.decode())
- file.seek(20)
- data = file.read()
- print(int.from_bytes(data, 'big'))
- text_data = "Hello, World!"
- number = 12345
-
- with open('binary_file.bin', 'wb') as file:
- file.write(text_data.encode())
- position = file.tell()
- byte_data = number.to_bytes(4, 'big')
- file.write(byte_data)
-
- with open('binary_file.bin', 'rb') as file:
- text = file.read(10)
- print(text.decode())
- file.seek(20)
- data = file.read()
- print(int.from_bytes(data, 'big'))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。