Python File read() Method

Python File(文件) 方法Python File Methods


Overview

read()The method is used to read a specified number of bytes from a file. If not given or negative, it reads all.

Syntax

The syntax of the read() method is as follows:

fileObject.read([size]); 

Parameters

  • size-- The number of bytes to read from the file. The default is -1, which means reading the entire file.

Return Value

Returns the bytes read from the string.

Example

The following example demonstrates the use of the read() method:

The content of the file example.txt is as follows:

1:www.example.com
2:www.example.com
3:www.example.com
4:www.example.com
5:www.example.com

Loop to read the content of the file:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Open the file
fo = open("example.txt", "rw+")
print File name:, fo.name

line = fo.read(10)
print Read string: %s % (line)

# Close the file
fo.close()

The output of the above example is:

文件名为:  example.txt
读取的字符串: 1:www.runo

Python File(文件) 方法Python File Methods

Other Extensions