LoginSignup
1
5

More than 5 years have passed since last update.

Python ファイル読み込み

Last updated at Posted at 2018-07-30

ファイルを読み込むときに結構忘れてしまうことが多いため個人用のメモとして作る。

Pythonでファイルを読み込む

ファイルtext.txtがあったとする。

text.txt
first line
second line

同じディレクトリにtext.pyを作り、以下のコードを実行する。

text.py
all = open('text.txt')
data = all.read()
all.close()

print(data)

結果:
first line
second line

のようにtext.txtの中の文章がそのまま吐き出される。

all.read()はallの文字をすべて読み込んでdataに入れている。では1行ずつ読み込みたいときはどうするべきか。

1行ずつ読み込みたい場合はreadline()を用いる。

text2.py
all = open('text.txt')
data = all.readline()
all.close()

print(data)

結果:
first line
のみ出力される。この後の行を読み込む際は再び
all.readline()
を実行すれバ良い。

1
5
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
1
5