Python seekable()の使い方|Trueになるもの・Falseになるもの一覧と「underlying stream is not seekable」の対処
Pythonのseekable()は、ファイルやストリームが位置の移動(seek)に対応しているかをTrue/Falseで返すメソッドです。Falseのストリームでseek()やtell()を呼ぶと「io.UnsupportedOperation: underlying stream is not seekable」になるので、事前の判定に使います。
通常のファイルはTrueですが、パイプで受け取った標準入力やHTTPのレスポンスはFalseになります。この記事では、どのオブジェクトがTrue/Falseになるかを実際に確かめた一覧と、Falseのときの対処法(BytesIOに読み込む)を、Python 3.12.15の実行結果つきで説明します(2026年10月18日確認)。
seekable()とは
公式ドキュメント(io — Core tools for working with streams、2026年10月18日確認)では、seekable()は「ストリームがランダムアクセスに対応していればTrueを返す。Falseならseek()・tell()・truncate()はOSErrorを送出する」と説明されています。ここでいうOSErrorの具体的な型が、OSErrorとValueErrorの両方を継承したio.UnsupportedOperationです。
with open("sample.txt", encoding="utf-8") as f:
print(f.seekable())
True
引数はなく、戻り値はTrueかFalseだけです。
seekable()がTrue/Falseになるもの一覧
よく使うオブジェクトで実際に試した結果です。
import io, gzip, os
with open("sample.txt", encoding="utf-8") as f:
print("text r :", f.seekable())
with open("sample.txt", "rb") as f:
print("binary r:", f.seekable())
with open("out.txt", "a", encoding="utf-8") as f:
print("text a :", f.seekable())
print("StringIO:", io.StringIO("abc").seekable())
print("BytesIO :", io.BytesIO(b"abc").seekable())
with gzip.open("s.gz", "wt", encoding="utf-8") as g:
g.write("hello\n")
with gzip.open("s.gz", "rt", encoding="utf-8") as g:
print("gzip r :", g.seekable())
r, w = os.pipe()
with os.fdopen(r, "rb") as pr:
print("os.pipe :", pr.seekable())
os.close(w)
text r : True
binary r: True
text a : True
StringIO: True
BytesIO : True
gzip r : True
os.pipe : False
| オブジェクト | seekable() | メモ |
|---|---|---|
open()したファイル(r・w・a、テキスト・バイナリ) |
True | 通常のディスク上のファイル |
io.StringIO/io.BytesIO |
True | メモリ上のデータ |
gzip.open()(読み込み) |
True | 読み込みモードで確認。圧縮ファイルでもTrueになる |
パイプ(os.pipe()、cat a.txt | python x.pyの標準入力) |
False | 流れてくるデータを一度しか読めない |
urllib.request.urlopen()のレスポンス |
False | ネットワークから順に届くデータ |
ソケット(socket.makefile()) |
False | 通信相手から順に届くデータ |
標準入力は「渡し方」で結果が変わる
同じsys.stdinでも、パイプで渡すかリダイレクトで渡すかで結果が変わります。
# sk.py
import sys
print("stdin seekable:", sys.stdin.seekable())
$ cat sample.txt | python sk.py
stdin seekable: False
$ python sk.py < sample.txt
stdin seekable: True
< sample.txtのリダイレクトでは、標準入力の中身が実際のファイルなのでシークできます。パイプでは前のコマンドの出力が流れてくるだけなので、戻れません。「手元で試すと動くのに、パイプでつなぐと落ちる」という不具合の多くはこの違いが原因です。
HTTPのレスポンスもFalse
import urllib.request
with urllib.request.urlopen("https://docs.python.org/3/", timeout=30) as res:
print(type(res).__name__, res.seekable())
try:
res.seek(0)
except Exception as e:
print(type(e).__module__ + "." + type(e).__name__, e)
HTTPResponse False
io.UnsupportedOperation seek
io.UnsupportedOperation: underlying stream is not seekable の原因
シークできないストリームでseek()やtell()を呼ぶと、次のエラーで止まります。
# sk3.py
import sys
data = sys.stdin.read()
sys.stdin.seek(0) # もう一度先頭から読もうとした
$ cat sample.txt | python sk3.py
sys.stdin.seek(0)
io.UnsupportedOperation: underlying stream is not seekable
パイプの標準入力でsys.stdin.tell()を呼んだ場合も、同じメッセージになりました。ライブラリの中でseek(0)を使っている関数(ファイルの種類を先頭のバイトで判定してから読み直す処理など)に、パイプやHTTPレスポンスをそのまま渡したときにも起こります。
対処法|BytesIOに読み込んでから使う
シークできないストリームは、一度全部読んでio.BytesIO(文字列ならio.StringIO)に入れ直すと、何度でも先頭に戻れるようになります。
# sk5.py
import sys, io
f = sys.stdin.buffer
print(type(f).__name__, f.seekable())
data = f.read()
buf = io.BytesIO(data)
print(type(buf).__name__, buf.seekable())
buf.seek(0)
print(buf.read().decode("utf-8"), end="")
$ cat sample.txt | python sk5.py
BufferedReader False
BytesIO True
りんご
バナナ
シークできるならそのまま使い、できないときだけメモリに読み込む、という関数にしておくと、ファイルでも標準入力でも同じように扱えます。
import io
def ensure_seekable(f):
if f.seekable():
return f
return io.BytesIO(f.read())
ただし、全体をメモリに載せるので、数GBあるような巨大なデータには向きません。その場合は一度だけ先頭から順に読む処理に書き換えるか、一時ファイル(tempfile.TemporaryFile())に書き出してから読み直します。
関連するメソッド
| メソッド | 調べること/すること |
|---|---|
readable() |
読み込めるか |
writable() |
書き込めるか |
seekable() |
位置を移動できるか |
seek() |
読み書きの位置を動かす |
tell() |
今の位置を返す |
seek()そのものの使い方(whenceやテキストモードの制限)は「Python seek()とは?」、標準入力の読み方は「Python sys.stdinとは?」で解説しています。
よくある質問
Q. seekable()がFalseになるのはどんなとき?
パイプで受け取った標準入力、os.pipe()、urlopen()のHTTPレスポンス、ソケットなど、データが順に流れてくるだけで先頭に戻れないストリームのときです。通常のファイルやBytesIOはTrueです。
Q. underlying stream is not seekable を直すには?
シークできないストリームでseek()やtell()を呼んでいるのが原因です。一度read()で全部読み、io.BytesIOに入れ直してから使うと、seek(0)で何度でも読み直せます。
Q. 標準入力はいつもseekable()がFalse?
いいえ。python x.py < file.txt のようにリダイレクトでファイルを渡した場合はTrueで、cat file.txt | python x.py のようにパイプで渡した場合はFalseでした。
Q. 書き込みモードのファイルもseekable()はTrue?
通常のファイルなら、w・aモードでもTrueです。ただしaモードでは、書き込みは常に末尾に追加されます。
seekable()のまとめ
seekable()は位置を移動できるかをTrue/Falseで返す- Falseのストリームで
seek()・tell()を呼ぶとio.UnsupportedOperation - パイプの標準入力・HTTPレスポンスはFalse、リダイレクトの標準入力はTrue
- Falseなら
io.BytesIO(f.read())に入れ直せば読み直せる
Pythonを独学で進めていてエラーで止まりがちな方は、テックジムの無料Python講座(ゼロからはじめるPython入門講座)を試してみるのもひとつの方法です。テックジムは永田町の東京本校で通える対面型のプログラミングスクールで、自分のペースで課題を進め、詰まったらトレーナーに質問できます。







