Python-file-readlines

提供:Dev Guides
移動先:案内検索

Pythonファイルreadlines()メソッド

説明

Pythonファイルメソッド* readlines()*は、readline()を使用してEOFまで読み取り、行を含むリストを返します。 オプションの_sizehint_引数が存在する場合、EOFまで読み取る代わりに、合計でおよそ_sizehint_バイトの行全体(おそらく内部バッファーサイズに切り上げた後)が読み取られます。

空の文字列が返されるのは、EOFがすぐに発生した場合だけです。

構文

以下は* readlines()*メソッドの構文です-

fileObject.readlines( sizehint );

パラメーター

  • sizehint -これは、ファイルから読み取るバイト数です。

戻り値

このメソッドは、行を含むリストを返します。

次の例は、readlines()メソッドの使用法を示しています。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readlines()
print "Read Line: %s" % (line)

line = fo.readlines(2)
print "Read Line: %s" % (line)

# Close opend file
fo.close()

上記のプログラムを実行すると、次の結果が生成されます-

Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']
Read Line: []