0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ファイルの読み込み、seekを使った移動

Last updated at Posted at 2020-08-25

ファイルをまとめて読み込み

qiita.py
with open("test.text", "r") as f:
    print(f.read())

一行ずつ読み込む

1行ずつ読み込みたい時はreadlineを使う
print関数でend=""とする理由としてはprint関数で改行が行われてしまうから

qiita.py
with open("test.text", "r") as f:
    while True:
        line = f.readline()
        print(line,end="")
        if not line:
            break

実行結果

AAA
BBB
CCC
DDD

end=""を使わないと

qiita.py
with open("test.text", "r") as f:
    while True:
        line = f.readline()
        print(line)
        if not line:
            break

実行結果

AAA

BBB

CCC

DDD

特定の文字数ごと読み込む

chunkを設定する
ネットワークの読み込みに使われる事も

qiita.py
with open("test.text", "r") as f:
    while True:
        chunk = 2
        line = f.read(chunk)
        print(line)
        if not line:
            break

実行結果

AA
A

BB
B

CC
C

DD
D

seekを使った移動

teil 現在の位置を返す
seek 任意の位置に移動することができる

qiita.py
with open("test.text", "r") as f:
    print(f.tell())
    #0
    print(f.read(1))
    #A
    f.seek(5)
    print(f.read(1))
    #B
    f.seek(14)
    print(f.read(1))
    #D
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?