read()方法从文件读取大小最多字节。如果读取可得到字节大小之前命中EOF,则它只读取可用的字节。
语法
以下是 read()方法的语法 -
fileObject.read( size );
参数
-
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