Python File read() Method
Overview
read() The method reads a specified number of bytes from a file; if not given or negative, it reads all.
Syntax
The read() method syntax is as follows:
fileObject.read([size]);
Parameters
-
size -- The number of bytes to read from the file; the default is -1, meaning read 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:
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
Read the file's contents in a loop:
Example
#!/usr/bin/python
-- coding: UTF-8 --
Opening a File
fo
=
open
(
"runoob.txt"
,
"rw+"
)
"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
读取的字符串: 1:www.runo
Python File methods