LoginSignup
2
2

More than 5 years have passed since last update.

Python > ファイルでなく複数行文字列から読込む > io.StringIO()

Last updated at Posted at 2017-07-21
動作環境
Python3 (ideone)

link

code

import io

emuCsv = """1,2,3
4,5,6
7,8,9"""

print('begin')
with io.StringIO(emuCsv) as fin:
    print(fin.read())

print('end')
run
begin
1,2,3
4,5,6
7,8,9
end

v0.2

import io

emuCsv = """1,2,3
4,5,6
7,8,9"""

print('begin')
with io.StringIO(emuCsv) as fin:
    print('line9')
    print(fin.read())

print('end')
run
begin
line9
1,2,3
4,5,6
7,8,9
end

fin.read()において3行分が一度にprint()されている。

上記の場合、with構文を使う意味はなさそうだ。

v0.3 > readline()使用

readline()というのがあるようだ。
https://stackoverflow.com/questions/7472839/python-readline-from-a-string

import io

emuCsv = """1,2,3
4,5,6
7,8,9"""

print('begin')
fin = io.StringIO(emuCsv)
print(fin.readline(),end='')
print(fin.readline(),end='')
print(fin.readline())
print('end')
run
begin
1,2,3
4,5,6
7,8,9
end

回数固定でreadline()を実行することはできる。
EOFについては不明。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2