티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How can I detect if a file is binary (non-text) in Python?
Python에서 파일이 이진 파일(텍스트가 아님)인지 어떻게 감지할 수 있을까요?
문제 내용
How can I tell if a file is binary (non-text) in Python?
Python에서 파일이 이진 파일(텍스트가 아님)인지 어떻게 알 수 있을까요?
I am searching through a large set of files in Python, and keep getting matches in binary files. This makes the output look incredibly messy.
Python에서 큰 파일 세트를 검색하고 이진 파일에서도 일치하는 결과가 나오는 문제가 있습니다. 이렇게 되면 출력물이 매우 어지럽게 보입니다.
I know I could use grep -I
, but I am doing more with the data than what grep allows for.
grep -I를 사용할 수는 있지만, 저는 데이터를 더 많이 처리해야 합니다.
In the past, I would have just searched for characters greater than 0x7f
, but utf8
and the like, make that impossible on modern systems. Ideally, the solution would be fast.
과거에는 문자가 0x7f보다 크다면 검색했지만, utf8과 같은 것들 때문에 현대 시스템에서는 이 방법이 불가능합니다. 이상적으로는 해결책이 빠르면 좋겠습니다.
높은 점수를 받은 Solution
Yet another method based on file(1) behavior:
또 다른 방법으로는 file(1) 동작을 기반으로 하는 방법이 있습니다.
>>> textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
>>> is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
Example:
예:
>>> is_binary_string(open('/usr/bin/python', 'rb').read(1024))
True
>>> is_binary_string(open('/usr/bin/dh_python3', 'rb').read(1024))
False
가장 최근 달린 Solution
from binaryornot.check import is_binary
is_binary('filename')
문서
출처 : https://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python
'개발 > 파이썬' 카테고리의 다른 글
파이썬에서 두 개의 리스트를 비교하고 일치하는 값을 반환하는 방법 (0) | 2023.02.24 |
---|---|
딕셔너리를 텍스트 파일로 쓰기 (0) | 2023.02.23 |
Python 사전(dictionary)에서 값에 대해 매핑(mapping)하는 방법 (0) | 2023.02.22 |
DataFrame의 문자열 열을 datetime으로 변환하기 (0) | 2023.02.22 |
'UserWarning: Could not import the lzma module ' 수정하기 (0) | 2023.02.21 |