0. Binary File이란
Binary file은 데이터를
- 텍스트 형식이 아닌
- 이진 형식(0과 1의 비트로 구성된 형식)으로 저장하는 파일.
Binary file (이진 파일)은
- 텍스트 파일과 달리 사람이 읽을 수 있는 문자로 표현되지 않으며,
- 특정 응용 프로그램이나 소프트웨어에 의해 해석되어야 함.
1. Binary File 처리하기
txt file과 거의 비슷하나, 다음의 차이를 보임.
- 파일 내용을 담는데 사용하는 class가
str
을 주로 쓰는 txt file의 경우와 달리bytes
와bytearray
를 사용한다.bytes
는 immutable이고,bytearray
는 mutable인 점을 기억할 것.
- txt file의 경우 글자수를 반환 또는 입력받는 것과 달리, byte 수를 사용함.
txt file을 읽고 쓰는 건 다음을 참고.
2023.07.04 - [Python] - [Python] Text File : read and write
[Python] Text File : read and write
쓰기 open으로 얻은 file object의 메서드 write 또는 print 함수를 통해 쓰기를 수행함. 당연히 해당 file object는 wt or w 등과 같이 Text file로 쓰기 (or a or x)등으로 열려야 함. print() 함수 standard output (stdout,
ds31x.tistory.com
당연하지만, binary file을 읽고 쓰려면 binary mode로 파일을 열어야 함.
2023.07.04 - [Python] - [Python] file : open and close
[Python] file : open and close
Python 에서 file을 처리하기 위해선 다른 프로그래밍 언어와 마찬가지로 file에 대한 접근이 가능한 object를 얻어와야함. 이같은 object는 file handler, file descriptor 등의 여러 이름으로 불리며, 이를 얻
ds31x.tistory.com
2. 쓰기
write
메서드를 이용한다.
# 32 bytes 의 데이터.
bin_data = bytearray(range(0,32))
# bin_data = bytes(bin_data)
with open('bfile.bin', 'wb') as fout:
cnt = fout.write(bin_data)
print(f'{cnt} bytes is written!')
write()
returns
the number of bytes written.
3. 읽기
read
메서드를 이용한다.
r_bin = bytes()
with open('bfile.bin', 'rb') as fin:
chunk = 5
while buf := fin.read(chunk):
r_bin += buf
print(len(r_bin))
print(list(map(int,r_bin)))
print(r_bin)
- 앞서 쓰기의 예제에서의 파일을 읽어들일 경우, 32 bytes를 읽어들이게 됨.
- EoF (end of file)에서 읽어들이게 된 경우 빈 bytes (empty bytes)를 반환.
- argument 없이
read()
를 사용할 경우, 전체를 한번에 읽어들임. (큰 사이즈의 파일을 읽을 경우 주의할 것.) - 맨 아래 line의 경우,
bytes
의 각 item이 byte들에 해당하는int
item을map
을 통해 얻고- 이들을 item으로 가지는
list
를 만들어 출력함.
참고: map사용법(high-order function)
같이 보면 좋은 자료들
2023.12.05 - [Python] - [Python] File Handling
[Python] File Handling
File 열고 닫기.2023.07.04 - [Python] - [Python] file : open and close [Python] file : open and closePython 에서 file을 처리하기 위해선 다른 프로그래밍 언어와 마찬가지로 file에 대한 접근이 가능한 object를 얻어와야
ds31x.tistory.com
2024.11.27 - [Python] - [Py] Serialization of Python: pickle
[Py] Serialization of Python: pickle
1. Python의 pickle 모듈Python의 pickle 모듈은 Python 객체를 직렬화(serialize)하여 파일 또는 메모리에 저장.저장된 데이터를 다시 역직렬화(deserialize)하여 원래 객체로 복원.데이터를 영구 저장하거나 네
ds31x.tistory.com
2024.01.15 - [Python] - [python] Text mode vs. Binary mode: File open
[python] Text mode vs. Binary mode: File open
Python에서 특정 파일을 open하는 경우,text mode 또는 binary mode 중 하나로 열게 된다. 이 둘의 차이점은 간단히 설명하면,현재 open하고자 하는 file을 text파일로 처리할지아니면 binary파일로 처리할지
ds31x.tistory.com
'Python' 카테고리의 다른 글
[Python] lambda expression and map, filter, reduce. (0) | 2023.07.07 |
---|---|
[Python] os 모듈의 함수들 : file과 directory 관련 (0) | 2023.07.04 |
[Python] Text File: read and write (0) | 2023.07.04 |
[Python] file: open and close (0) | 2023.07.04 |
[Python] Regular Expression : 표현식 기초 및요약 (0) | 2023.07.03 |