Python3 File read() Method
Overview
read() The method reads the specified number of characters (text mode t) or bytes (binary mode b) from a file; if the argument is not given or size or size is negative, it reads the entire file.
Syntax
The read() method syntax is as follows:
fileObject.read([size]);
Parameters
-
size -- the number of characters (text mode) or bytes (binary mode) to read from the file, defaulting to -1, which means reading the entire file.
Return Value
Returns the bytes read from the string.
Example
The following example shows how to use the read() method:
The contents of the runoob.txt file are as follows:
这是第一行
这是第二行
这是第三行
这是第四行
这是第五行
Read the file's contents in a loop:
Example
#!/usr/bin/python3
Opening a File
fo
=
open
(
"runoob.txt"
,
"r+"
)
(
"File name: "
,
fo.
name
)
line
=
fo.
read
(
10
)
(
"String read: %s"
%
(
line
)
)
Closing a File
fo.
close
(
)
The output of the above example is:
文件名为: runoob.txt
读取的字符串: 这是第一行
这是第二
Python3 File methods