티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How do I wrap a string in a file in Python?
파이썬에서 문자열을 파일로 래핑하는 방법은 무엇인가요?
문제 내용
How do I create a file-like object (same duck type as File) with the contents of a string?
어떻게 문자열의 내용을 가진 파일과 같은 duck type의 파일과 유사한 객체를 생성할 수 있나요?
높은 점수를 받은 Solution
For Python 2.x, use the StringIO module. For example:
Python 2.x에서는 StringIO 모듈을 사용합니다. 예를 들면:
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
I use cStringIO (which is faster), but note that it doesn't accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)
cStringIO를 사용합니다(이게 더 빠릅니다) 하지만, ASCII 문자열로 인코딩할 수 없는 유니코드 문자열은 받아들이지 않습니다. ("from cStringIO"를 "from StringIO"로 바꾸면 StringIO로 전환할 수 있습니다.)
For Python 3.x, use the io
module.
Python 3.x에서는 io 모듈을 사용합니다.
f = io.StringIO('foo')
가장 최근 달린 Solution
If your file-like object is expected to contain bytes, the string should first be encoded as bytes, and then a BytesIO object can be used instead. In Python 3:
파일 유사 객체가 바이트를 포함해야 할 경우, 문자열은 먼저 바이트로 인코딩되어야 하며, 그 후에 BytesIO 객체를 대신 사용할 수 있습니다.
Python 3에서:
from io import BytesIO
string_repr_of_file = 'header\n byline\n body\n body\n end'
function_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))
출처 : https://stackoverflow.com/questions/141449/how-do-i-wrap-a-string-in-a-file-in-python
'개발 > 파이썬' 카테고리의 다른 글
pip를 사용하여 Scipy 설치할 때 오류 수정하기 (0) | 2023.02.19 |
---|---|
두 개의 딕셔너리를 연결하여 새로운 딕셔너리를 만들기 (0) | 2023.02.18 |
'sphinx-build fail - autodoc can't import/find module' 오류 수정하기 (0) | 2023.02.17 |
문자열에서 Pandas DataFrame 만들기 (0) | 2023.02.17 |
데이터 프레임에 빈 열을 추가하는 방법 (0) | 2023.02.17 |