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?

【Python】open関数

Posted at

open関数でテキストファイルを取得すると、改行で区切られたイテラブルオブジェクトが返ります。

with open('sample.txt') as f:

f
▶︎
<_io.TextIOWrapper name='sample.txt' mode='r' encoding='UTF-8'>

このイテラブルオブジェクトに対して、read、readline、readlinesメソッドで処理した違いは以下です。

■ read
テキスト全体もしくは指定した文字数のテキストを、文字列で取得する。
文字数を指定する場合はread(100)のように引数で指定する。

■ readline
一行ずつ文字列で取得する。
readやreadlinesでテキスト全体を取得すると、文字数によっては処理できないことがあるため、その場合はreadlineで一行ずつ取得する。

■ readlines
テキスト全体を行ごとに分割して、文字列のリストで取得する。

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?