在Python中操作文件之read()方法的使用教程

yipeiwu_com6年前Python基础

 read()方法读取文件size个字节大小。如果读取命中获得EOF大小字节之前,那么它只能读取可用的字节。
语法

以下是read()方法的语法:

fileObject.read( size );

参数

  •     size -- 这是可以从文件中读取的字节数。

返回值

此方法返回读取字符串中的字节数。
例子

下面的例子显示了read()方法的使用。

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

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

# Close opend file
fo.close()

当我们运行上面的程序,它会产生以下结果:

Name of the file: foo.txt
Read Line: This is 1s

相关文章

python 捕获 shell/bash 脚本的输出结果实例

#!/usr/bin/python ## get subprocess module import subprocess   ## call date command ##...

Python实现提取XML内容并保存到Excel中的方法

Python实现提取XML内容并保存到Excel中的方法

本文实例讲述了Python实现提取XML内容并保存到Excel中的方法。分享给大家供大家参考,具体如下: 最近做一个项目是解析XML文件,提取其中的chatid和lt、timestamp...

python高手之路python处理excel文件(方法汇总)

python高手之路python处理excel文件(方法汇总)

用python来自动生成excel数据文件。python处理excel文件主要是第三方模块库xlrd、xlwt、xluntils和pyExcelerator,除此之外,python处理e...

详解python并发获取snmp信息及性能测试

python & snmp 用python获取snmp信息有多个现成的库可以使用,其中比较常用的是netsnmp和pysnmp两个库。网上有较多的关于两个库的例子。 本文重点在于如何并...

python绘制规则网络图形实例

我就废话不多说,直接上代码吧! #Copyright (c)2017, 东北大学软件学院学生 # All rightsreserved #文件名称:a.py # 作 者:孔云 #问...