在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实现的阳历转阴历(农历)算法

搜索了好几个python实现的万年历多有部分时间有问题,好多是来自这个代码: 复制代码 代码如下:#!/usr/bin/env python# -*- coding: utf-8 -*-...

详解Python下载图片并保存本地的两种方式

一:使用Python中的urllib类中的urlretrieve()函数,直接从网上下载资源到本地,具体代码: import os,stat import urllib.reques...

python对于requests的封装方法详解

由于requests是http类接口的核心,因此封装前考虑问题比较多: 1. 对多种接口类型的支持; 2. 连接异常时能够重连; 3. 并发处理的选择; 4. 使用方便,容易维护; 当前...

python实现俄罗斯方块游戏

python实现俄罗斯方块游戏

在公司实习。公司推崇Python和Django框架,所以也得跟着学点。 简单瞅了下Tkinter,和Canvas配合在一起,还算是简洁的界面开发API。threading.Thread创...

YUV转为jpg图像的实现

调用opencv库,将yuv图像转为jpg图像。 代码如下: # define _CRT_SECURE_NO_WARNINGS #include <string> #in...