Python-file-readline

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

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

説明

Pythonファイルメソッドreadline()は、ファイルから1行全体を読み取ります。 末尾の改行文字は文字列に保持されます。 _size_引数が存在し、負でない場合、末尾の改行を含む最大バイト数であり、不完全な行が返される場合があります。

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

構文

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

fileObject.readline( size );

パラメーター

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

戻り値

このメソッドは、ファイルから読み取った行を返します。

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

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.readline()
print "Read Line: %s" % (line)

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

# Close opend file
fo.close()

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

Name of the file: foo.txt
Read Line: This is 1st line

Read Line: This