Python-file-next

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

Pythonファイルのnext()メソッド

説明

Pythonファイルメソッド* next()*は、ファイルが反復子として使用される場合に使用されます。通常はループ内で、next()メソッドが繰り返し呼び出されます。 このメソッドは次の入力行を返すか、EOFがヒットしたときに_StopIteration_を発生させます。

next()メソッドを_readline()_などの他のファイルメソッドと組み合わせても、正しく機能しません。 ただし、seek()を使用してファイルを絶対位置に再配置すると、先読みバッファーがフラッシュされます。

構文

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

fileObject.next();

パラメーター

  • NA

戻り値

このメソッドは、次の入力行を返します。

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

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

for index in range(5):
   line = fo.next()
   print "Line No %d - %s" % (index, line)

# Close opend file
fo.close()

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

Name of the file:  foo.txt
Line No 0 - This is 1st line

Line No 1 - This is 2nd line

Line No 2 - This is 3rd line

Line No 3 - This is 4th line

Line No 4 - This is 5th line