Latest web development tutorials

Python File read() 方法

Python File(文件) 方法 Python File(文件)方法


概述

read()方法用於從文件讀取指定的字節數,如果未給定或為負則讀取所有。

語法

read() 方法語法如下:

fileObject.read(); 

參數

  • size --從文件中讀取的字節數。

返回值

返回從字符串中讀取的字節。

實例

以下實例演示了read() 方法的使用:

文件w3big.txt 的內容如下:

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

循環讀取文件的內容:

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

# 打开文件
fo = open("w3big.txt", "rw+")
print "文件名为: ", fo.name

line = fo.read(10)
print "读取的字符串: %s" % (line)

# 关闭文件
fo.close()

以上實例輸出結果為:

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

Python File(文件) 方法 Python File(文件)方法