0
3

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.

ファイルの読み込み

Posted at
1
s = """\
AAA
BBB
CCC
DDD
"""

with open('test.txt', 'w') as f:
    f.write(s)

with open('test.txt', 'r') as f:
    while True:
        line = f.readline()
        print(line, end="")
        
        if not line:
            break
1の実行結果
AAA
BBB
CCC
DDD
with open('test.txt', 'w') as f:
    f.write(s)

でtest.txtという中身が
AAA
BBB
CCC
DDD
であるテキストファイルが作成される。

そして、

with open('test.txt', 'r') as f:

でtest.txtの中身をfとして読み込み、

while True:
        line = f.readline()
        print(line, end="")

        if not line:
            break

で、
変数lineにtest.txtの中身を一行ずつ格納して出力。
lineの中身がなくなるなでループさせて、
なくなったらブレイク。

2
s = """\
AAA
BBB
CCC
DDD
"""

with open('test.txt', 'w') as f:
    f.write(s)

with open('test.txt', 'r') as f:
    while True:
        chunk = 2
        line = f.read(chunk)
        print(line)
        
        if not line:
            break
2の実行結果
AA
A

BB
B

CC
C

DD
D

二文字ずつ出力させたもの。

A2つ
Aと改行
B2つ
Bと改行
C2つ
Cと改行
D2つ
Dと改行

0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?