IT

대체 바이너리 파일에 쓰는 방법?

lottoking 2020. 8. 19. 18:53
반응형

대체 바이너리 파일에 쓰는 방법?


정수로 바이트 목록이 있습니다.

[120, 3, 255, 0, 100]

이 목록을 바이너리로 파일에 어떻게 쓸 수 있습니까?

작동할까요?

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(newFileBytes)

이 정확히 무엇을 위한 것입니다 :bytearray

newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)

파이썬 3.x를 사용를 bytes하는 경우 대신 사용할 수 있습니다 (를 더 잘 의도 알릴 수 있으므로 그래야 흥분이합니다). 그러나 파이썬 2.X에서, 즉하지 않습니다 작품은, 때문에이 bytes단지의 별칭입니다 str. 더와 같이 인터랙티브 인터프리터로 그래픽 텍스트로 설명하는 것보다 쉽기 때문에 그렇게하겠습니다.

Python 3.x :

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'

Python 2.x :

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'

사용 후 바이트 쓰기, 이진 바이트로 정수 값을 변환 할 수 있습니다. struct.pack

newFile.write(struct.pack('5B', *newFileBytes))

바이너리 파일에 그러나 .txt확장자를 주지 않을을 구석으로 입니다.

이 방법의 장점은 다른 유형이라고하는 것입니다. 예를 들어 값이 255보다 큰 경우 '5i'전체 32 비트 정수를 가져 오는 대신 형식에 사용할 수 있습니다 .


256의 정수에서 이진수로 변환하려는 chr함수를 사용하십시오 . 그래서 당신은 다음을보고 있습니다.

newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))

Python 3.2 이상에서는 기본 int 메소드를 사용 하여이 작업을 수행 할 수도 있습니다 .to_bytes

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

즉, 이 경우에 대한 각 단일 호출 은 정수 값을 대규모 엔디안 순서 (길이 1 많은 경우 사소한)로 배열 된 문자로 길이 1의 호스트를 생성합니다 . 마지막 두 줄을 단일 줄로 연속 수도 있습니다.to_bytesbyte

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

Python 3 구문을 사용하여 다음 코드 예제를 사용할 수 있습니다.

from struct import pack
with open("foo.bin", "wb") as file:
  file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))

다음은 쉘 한 줄입니다.

python -c $'from struct import pack\nwith open("foo.bin", "wb") as file: file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))'

다음과 같이 pickle을 사용하십시오. 수입 피클

코드는 다음과 가변적입니다.

import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
    pickle.dump(mybytes, mypicklefile)

데이터를 다시 사용하려면 pickle.load 메소드를 사용하십시오.

참고 URL : https://stackoverflow.com/questions/18367007/python-how-to-write-to-a-binary-file

반응형