개발/파이썬

파이썬3에서 StringIO 사용 방법

맨날치킨 2022. 11. 26. 08:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to use StringIO in Python3?

파이썬3에서 StringIO 사용 방법

 문제 내용 

I am using Python 3.2.1 and I can't import the StringIO module. I use io.StringIO and it works, but I can't use it with numpy's genfromtxt like this:

Python 3.2.1을 사용하고 있는데 StringIo 모듈을 가져올 수 없습니다. io.StringIO와 그것은 작동하지만, 나는 이렇게 taxt의 numpy's genfromtxt와 함께 사용할 수 없다:

 

x="1 3\n 4.5 8"        
numpy.genfromtxt(io.StringIO(x))

I get the following error:

다음 오류가 발생합니다.

 

TypeError: Can't convert 'bytes' object to str implicitly  

and when I write import StringIO it says

StringIO를 import하려고 작성 할 때 아래 메시지가 발생합니다.

 

ImportError: No module named 'StringIO'

 

 

 높은 점수를 받은 Solution 

when i write import StringIO it says there is no such module.

StringIO 모듈을 import하려고 할 때 해당 모듈이 없다고 표시됩니다.

 

From What’s New In Python 3.0:

Python 3.0의 새로운 기능:

 

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

StringIO 및 cStringIO 모듈이 없습니다. 대신 io 모듈을 가져오고 텍스트와 데이터에 각각 io.StringIO 또는 io.BytesIO를 사용하세요.

 

.

.

 


A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):

파이썬 3에서 동작하도록 파이썬 2 코드를 수정하는 데 유용한 방법:

 

try:
    from StringIO import StringIO ## for Python 2
except ImportError:
    from io import StringIO ## for Python 3

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

참고: 이 예는 질문의 주요 이슈와 접할 수 있으며 누락된 문자열을 일반적으로 해결할 때 고려해야 할 사항으로만 포함됩니다.IO 모듈. 보다 직접적인 해결책을 보려면 TypeError: 메시지를 입력하십시오. 'bytes' 개체를 암시적으로 str로 변환할 수 없습니다. 이 대답을 참조하십시오.

 

 

 

 가장 최근 달린 Solution 

Roman Shapovalov's code should work in Python 3.x as well as Python 2.6/2.7. Here it is again with the complete example:

로만 샤포발로프의 코드는 파이썬 2.6/2.7 뿐만 아니라 파이썬 3.x에서도 작동해야 한다. 여기 완전한 예가 있습니다.

 

import io
import numpy
x = "1 3\n 4.5 8"
numpy.genfromtxt(io.BytesIO(x.encode()))

Output:

출력:

 

array([[ 1. ,  3. ],
       [ 4.5,  8. ]])

Explanation for Python 3.x:

파이썬 3.x에 대한 설명:

 

  • numpy.genfromtxt takes a byte stream (a file-like object interpreted as bytes instead of Unicode).
  • io.BytesIO takes a byte string and returns a byte stream. io.StringIO, on the other hand, would take a Unicode string and and return a Unicode stream.
  • x gets assigned a string literal, which in Python 3.x is a Unicode string.
  • encode() takes the Unicode string x and makes a byte string out of it, thus giving io.BytesIO a valid argument.
numpy.genfromtx는 바이트 스트림(유니코드 대신 바이트로 해석되는 파일 같은 객체)을 취한다. io.바이트IO는 바이트 문자열을 가져와서 바이트 스트림을 반환합니다. io.String반면 IO는 유니코드 문자열을 가져와서 유니코드 스트림을 반환합니다. x는 문자열 리터럴을 할당받는데, 파이썬 3.x에서는 유니코드 문자열이다. encode()는 유니코드 문자열 x를 가져와서 바이트 문자열을 만든다.바이트 IO 유효한 인수입니다.

 

The only difference for Python 2.6/2.7 is that x is a byte string (assuming from __future__ import unicode_literals is not used), and then encode() takes the byte string x and still makes the same byte string out of it. So the result is the same.

파이썬 2.6/2.7의 유일한 차이점은 x가 바이트 문자열(_future_import unicode_literals에서 사용되지 않는다고 가정)이고, encode()가 바이트 문자열 x를 가져와서 동일한 바이트 문자열을 만든다는 것이다. 그래서 결과는 같다.

 


Since this is one of SO's most popular questions regarding StringIO, here's some more explanation on the import statements and different Python versions.

String에 관한 SO의 가장 인기 있는 질문 중 하나이기 때문입니다.IO, 가져오기 문과 다양한 Python 버전에 대한 몇 가지 설명이 있습니다.

 

Here are the classes which take a string and return a stream:

다음은 문자열을 가져와서 스트림을 반환하는 클래스입니다.

 

  • io.BytesIO (Python 2.6, 2.7, and 3.x) - Takes a byte string. Returns a byte stream.
  • io.StringIO (Python 2.6, 2.7, and 3.x) - Takes a Unicode string. Returns a Unicode stream.
  • StringIO.StringIO (Python 2.x) - Takes a byte string or Unicode string. If byte string, returns a byte stream. If Unicode string, returns a Unicode stream.
  • cStringIO.StringIO (Python 2.x) - Faster version of StringIO.StringIO, but can't take Unicode strings which contain non-ASCII characters.
io.바이트IO(Python 2.6, 2.7 및 3.x) - 바이트 문자열을 사용합니다. 바이트 스트림을 반환합니다. io.StringIO(Python 2.6, 2.7 및 3.x) - 유니코드 문자열을 사용합니다. 유니코드 스트림을 반환합니다. StringIO.StringIO(Python 2.x) - 바이트 문자열 또는 유니코드 문자열을 사용합니다. 바이트 문자열인 경우 바이트 스트림을 반환합니다. 유니코드 문자열인 경우 유니코드 스트림을 반환합니다. cStringIO.StringIO(Python 2.x) - String의 빠른 버전IO.StringIO, 그러나 ASC가 아닌 유니코드 문자열을 사용할 수 없음2자.

 

Note that StringIO.StringIO is imported as from StringIO import StringIO, then used as StringIO(...). Either that, or you do import StringIO and then use StringIO.StringIO(...). The module name and class name just happen to be the same. It's similar to datetime that way.

문자열에 유의하십시오.IO.StringIO를 String에서 가져옵니다.IO 가져오기 문자열IO, 그런 다음 StringIO(...)로 사용됩니다. 또는 문자열 가져오기를 수행합니다.IO 후 String 사용IO.StringIO(...)입니다. 모듈 이름과 클래스 이름이 동일합니다. 그런 식으로 데이트 시간과 비슷해요.

 

What to use, depending on your supported Python versions:

지원되는 Python 버전에 따라 사용할 항목:

 

  • If you only support Python 3.x: Just use io.BytesIO or io.StringIO depending on what kind of data you're working with.
  • If you support both Python 2.6/2.7 and 3.x, or are trying to transition your code from 2.6/2.7 to 3.x: The easiest option is still to use io.BytesIO or io.StringIO. Although StringIO.StringIO is flexible and thus seems preferred for 2.6/2.7, that flexibility could mask bugs that will manifest in 3.x. For example, I had some code which used StringIO.StringIO or io.StringIO depending on Python version, but I was actually passing a byte string, so when I got around to testing it in Python 3.x it failed and had to be fixed.Note that if you import BytesIO or StringIO from six, you get StringIO.StringIO in Python 2.x and the appropriate class from io in Python 3.x. If you agree with my previous paragraphs' assessment, this is actually one case where you should avoid six and just import from io instead.
  • Another advantage of using io.StringIO is the support for universal newlines. If you pass the keyword argument newline='' into io.StringIO, it will be able to split lines on any of \n, \r\n, or \r. I found that StringIO.StringIO would trip up on \r in particular.
  • If you support Python 2.5 or lower and 3.x: You'll need StringIO.StringIO for 2.5 or lower, so you might as well use six. But realize that it's generally very difficult to support both 2.5 and 3.x, so you should consider bumping your lowest supported version to 2.6 if at all possible.
Python 3.x만 지원하는 경우: io를 사용하십시오.바이트 IO 또는 IO.작업 중인 데이터의 종류에 따라 IO를 문자열화합니다. Python 2.6/2.7과 3.x를 모두 지원하거나 코드를 2.6/2.7에서 3.x로 전환하려는 경우: 가장 쉬운 옵션은 여전히 io를 사용하는 것입니다.바이트 IO 또는 IO.StringIO. 문자열이긴 하지만IO.StringIO는 유연하므로 2.6/2.7에서 선호되는 것으로 보이며, 유연성은 3.x에서 나타날 버그를 가릴 수 있습니다. 예를 들어 String을 사용하는 코드가 몇 개 있었습니다.IO.StringIO 또는 IO.StringIO는 Python 버전에 따라 다르지만, 실제로 바이트 문자열을 전달하고 있었기 때문에 Python 3.x에서 테스트할 때 실패하여 수정해야 했습니다. io를 사용하는 또 다른 장점.StringIO는 범용 신규 라인을 지원합니다. 키워드 인수 newline='을 io로 전달하면.문자열 IO, \n, \r\n 또는 \r 중 하나에서 선을 분할할 수 있습니다. 나는 그 스트링을 찾았다.IO.StringIO는 특히 \r에 걸려 넘어집니다. 바이트를 가져올 경우IO 또는 문자열6번부터 IO하면 String을 얻을 수 있습니다.IO.String파이썬 2.x의 IO와 파이썬 3.x의 해당 클래스. 만약 당신이 내 이전 단락들의 평가에 동의한다면, 이것은 실제로 당신이 6개를 피하고 대신 io에서 가져오기만 해야 하는 한 가지 경우이다. Python 2.5 이하 및 3.x를 지원하는 경우: String이 필요합니다.IO.StringIO는 2.5 이하이므로 6개를 사용하는 것이 좋습니다. 그러나 일반적으로 2.5와 3.x를 모두 지원하는 것은 매우 어려운 일이므로 가능하면 지원되는 최저 버전을 2.6으로 변경하는 것을 고려해야 합니다.

 

 

 

출처 : https://stackoverflow.com/questions/11914472/how-to-use-stringio-in-python3

반응형