programing

파이썬은 바이너리 파일에 어떻게 쓰나요?

minimums 2023. 6. 22. 21:38
반응형

파이썬은 바이너리 파일에 어떻게 쓰나요?

나는 정수로 바이트 목록을 가지고 있는데, 이것은 다음과 같습니다.

[120, 3, 255, 0, 100]

이 목록을 이진 파일로 작성하려면 어떻게 해야 합니까?

이것이 효과가 있을까요?

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

이는 바로 다음과 같은 목적입니다.

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

Python 3.x를 사용하는 경우bytes대신에 (그리고 아마도, 그것이 당신의 의도를 더 잘 나타내므로, 아마도 그래야 할 것입니다.)하지만 Python 2.x에서는 작동하지 않습니다. 왜냐하면bytes의 별칭일 뿐입니다.str평소처럼 텍스트로 설명하는 것보다 대화형 통역사로 보여주는 것이 더 쉬우니, 그냥 그렇게 하겠습니다.

파이썬 3.x:

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

파이썬 2.x:

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

정수 값을 이진 바이트로 변환한 다음 바이트를 씁니다.예.

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

하지만 나는 바이너리 파일을 절대 주지 않을 것입니다..txt연장의

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

Python 3.2+에서는 native int 메서드를 사용하여 이를 수행할 수도 있습니다.

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 문자열의 경우는 사소한 것입니다). 이 문자열은 정수 값을 나타냅니다.byte마지막 두 줄을 하나의 줄로 줄일 수도 있습니다.

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

256 미만의 정수에서 2진수로 변환하려면 다음을 사용합니다.chr기능.그래서 여러분은 다음과 같은 일을 하고 있습니다.

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

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])))'

피클 사용: 피클 가져오기

코드는 다음과 같습니다.

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

데이터를 다시 읽으려면 pickle.load 메서드를 사용합니다.

int 배열을 파일에 쓸 수 있는 편리한 기능,

def write_array(fname,ray):
    '''
    fname is a file pathname
    ray is an array of int
    '''
    print("write:",fname)
    EncodeInit()
    buffer = [ encode(z) for z in ray ]
    some = bytearray(buffer)
    immutable = bytes(some)
    with open(fname,"wb") as bfh:
        wc = bfh.write(immutable)
        print("wrote:",wrote)
    return wc

함수 호출 방법,

write_array("data/filename",[1,2,3,4,5,6,7,8])

읽기 쉬운 인코딩/디코드를 위해 클래스에 다음을 묶습니다.

Encode = {}
Decode = {}
def EncodeInit():
    '''
    Encode[] 0:62 as 0-9A-Za-z
    Decode[] 0-9A-Za-z as 0:62
    '''
    for ix in range( 0,10): Encode[ix] = ix+ord('0')
    for ix in range(10,36): Encode[ix] = (ix-10)+ord('A')
    for ix in range(36,62): Encode[ix] = (ix-36)+ord('a')
    for ix in range( 0,10): Decode[ix+ord('0')] = ix
    for ix in range(10,36): Decode[(ix-10)+ord('A')] = ix
    for ix in range(36,62): Decode[(ix-36)+ord('a')] = ix

def encode(x):
    '''
    Encode[] 0:62 as 0-9A-Za-z
    Otherwise '.'
    '''
    if x in Encode: return Encode[x]
    # else: error
    return ord('.')

def decode(x):
    '''
    Decode[] 0-9A-Za-z as 0:62
    Otherwise -1
    '''
    if x in Decode: return Decode[x]
    # else: error
    return -1

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

반응형