Python-file-read

提供:Dev Guides
2020年6月22日 (月) 22:34時点におけるMaintenance script (トーク | 投稿記録)による版 (Imported from text file)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
移動先:案内検索

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

説明

Pythonファイルメソッド* read()*は、ファイルから最大_size_バイトを読み取ります。 読み取りがsizeバイトを取得する前にEOFにヒットした場合、使用可能なバイトのみを読み取ります。

構文

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

fileObject.read( size );

パラメーター

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

戻り値

このメソッドは、文字列で読み取られたバイトを返します。

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

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

# Close opend file
fo.close()

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

Name of the file:  foo.txt
Read Line: Python is