Python 3 - 文件 read() 方法
-
描述
方法read()从文件中读取最多size个字节。如果在获取大小字节之前读取命中 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