binary file을 읽고 쓰는 건 text file을 읽고 쓰는 것과 유사하나, bytes 객체 들을 통해 이루어지며, 글자가 아닌 byte 단위를 사용한다는 점이 차이점임.

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
Python에서 Text File을 읽고 쓰는 것은 io.TextIOWrapper 객체를 이용하며 문자 기반의 stream 으로 이루어짐.개행문자를 기반으로 flush가 이루어지는 line_buffering을 사용 가능함 (line_buffering=True 로 설정시).
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 object, file handler, file descriptor 등의 여러 이름으로 불리며,P
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들에 해당하는intitem을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 관련 (1) | 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 |