Python3-file-read
提供:Dev Guides
Python 3-ファイルのread()メソッド
説明
メソッド* read()*は、ファイルから最大で_size_バイトを読み取ります。 読み取りがsizeバイトを取得する前にEOFにヒットした場合、使用可能なバイトのみを読み取ります。
構文
以下は* read()*メソッドの構文です-
fileObject.read( size );
パラメーター
サイズ-これは、ファイルから読み取るバイト数です。
戻り値
このメソッドは、文字列で読み取られたバイトを返します。
例
次の例は、read()メソッドの使用法を示しています。
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.read(10)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
結果
上記のプログラムを実行すると、次の結果が生成されます-
Name of the file: foo.txt
Read Line: This is 1s