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


Posted in Python onMay 24, 2015

 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 相关文章推荐
Python标准库之多进程(multiprocessing包)介绍
Nov 25 Python
python实现读取大文件并逐行写入另外一个文件
Apr 19 Python
Python学习小技巧总结
Jun 10 Python
Python subprocess模块常见用法分析
Jun 12 Python
Python实现快速计算词频功能示例
Jun 25 Python
python使用udp实现聊天器功能
Dec 10 Python
python实现连续图文识别
Dec 18 Python
python SQLAlchemy 中的Engine详解
Jul 04 Python
python集合常见运算案例解析
Oct 17 Python
Python一行代码解决矩阵旋转的问题
Nov 30 Python
使用opencv将视频帧转成图片输出
Dec 10 Python
手把手教你实现PyTorch的MNIST数据集
Jun 28 Python
在Python中使用next()方法操作文件的教程
May 24 #Python
在Python程序中操作文件之isatty()方法的使用教程
May 24 #Python
讲解Python中fileno()方法的使用
May 24 #Python
在Python程序中操作文件之flush()方法的使用教程
May 24 #Python
Python编程中用close()方法关闭文件的教程
May 24 #Python
详细讲解Python中的文件I/O操作
May 24 #Python
详解在Python中处理异常的教程
May 24 #Python
You might like
php 在线导入mysql大数据程序
2015/06/11 PHP
Zend Framework入门教程之Zend_Db数据库操作详解
2016/12/08 PHP
javascript parseInt 大改造
2009/09/27 Javascript
javascript 学习笔记(八)javascript对象
2011/04/12 Javascript
JS扩展方法实例分析
2015/04/15 Javascript
jQuery mobile转换url地址及获取url中目录部分的方法
2015/12/04 Javascript
AngularJS 让人爱不释手的八种功能
2016/03/23 Javascript
使用Promise解决多层异步调用的简单学习心得
2016/05/17 Javascript
jquery DataTable实现前后台动态分页
2017/06/17 jQuery
element-ui中select组件绑定值改变,触发change事件方法
2018/08/24 Javascript
详解express使用vue-router的history踩坑
2019/06/05 Javascript
js实现文字头像的生成代码
2020/03/07 Javascript
[05:13]2018DOTA2亚洲邀请赛主赛事第二日战况回顾 LGD、VG双雄携手晋级
2018/04/05 DOTA
Python实现的数据结构与算法之链表详解
2015/04/22 Python
Python实现的HTTP并发测试完整示例
2020/04/23 Python
Python 文件处理注意事项总结
2017/04/10 Python
用python做一个搜索引擎(Pylucene)的实例代码
2017/07/05 Python
python+django+sql学生信息管理后台开发
2018/01/11 Python
对python制作自己的数据集实例讲解
2018/12/12 Python
python的pytest框架之命令行参数详解(上)
2019/06/27 Python
使用python搭建服务器并实现Android端与之通信的方法
2019/06/28 Python
python的faker库用法
2019/11/28 Python
解决Python 异常TypeError: cannot concatenate 'str' and 'int' objects
2020/04/08 Python
如何理解python面向对象编程
2020/06/01 Python
如何快速一次性卸载所有python包(第三方库)呢
2020/10/20 Python
瑞典快乐袜子:Happy Socks
2018/02/16 全球购物
在对linux系统分区进行格式化时需要对磁盘簇(或i节点密度)的大小进行选择,请说明选择的原则
2012/01/13 面试题
大一自我鉴定范文
2013/10/04 职场文书
五五普法心得体会
2014/09/04 职场文书
自我检讨报告
2015/01/28 职场文书
学生会干部任命书
2015/09/21 职场文书
windows安装python超详细图文教程
2021/05/21 Python
Redis高级数据类型Hyperloglog、Bitmap的使用
2021/05/24 Redis
Golang中channel的原理解读(推荐)
2021/10/16 Golang
将MySQL的表数据全量导入clichhouse库中
2022/03/21 MySQL
Java数组详细介绍及相关工具类
2022/04/14 Java/Android