Python-基础-文件操作-随机存取
随机存取
文件操作中,read()和write()都属于顺序存取,只能按顺序从头到尾的进行读写。实际上我们可以只访问文件中我们感兴趣的部分。对此,我们可以使用seek()和tell()方法。两种方法的help()返回结果如下。
>>> f = open("demo.txt","w")
>>> f.write("")
10
>>> f.close()
>>> help(f.seek)
Help on built-in function seek: seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
Change stream position. Change the stream position to the given byte offset. The offset is
interpreted relative to the position indicated by whence. Values
for whence are: * 0 -- start of stream (the default); offset should be zero or positive
* 1 -- current stream position; offset may be negative
* 2 -- end of stream; offset is usually negative Return the new absolute position.
>>> help(f.tell)
Help on built-in function tell: tell() method of _io.TextIOWrapper instance
Return current stream position.
seek的第一个参数——cookie——用来指示相对位移,可正可负可零,受限于第二个参数。必需。
seek的第二个参数——whence——用来指示参照物,0(io.SEEK_SET)代表文件开头,1(io.SEEK_CUR)代表当前位置,2(io.SEEK_END)代表文件末尾。默认为0。
>>> f = open("demo.txt","r")
>>> f.seek(0)
0
>>> f.seek(-1)
Traceback (most recent call last):
File "<pyshell#135>", line 1, in <module>
f.seek(-1)
ValueError: negative seek position -1
>>> f.seek(1)
1
默认/whence=0情况,相对位移只能为零或正数。
>>> f = open("demo.txt","r")
>>> f.seek(0,1)
0
>>> f.seek(-1,1)
Traceback (most recent call last):
File "<pyshell#126>", line 1, in <module>
f.seek(-1,1)
io.UnsupportedOperation: can't do nonzero cur-relative seeks
>>> f.seek(1,1)
Traceback (most recent call last):
File "<pyshell#127>", line 1, in <module>
f.seek(1,1)
io.UnsupportedOperation: can't do nonzero cur-relative seeks
当前/whence=1情况,相对位移只能为零。这是令人感到奇怪的,原因会在后面讲。
>>> f = open("demo.txt","r")
>>> f.seek(0,2)
10
>>> f.seek(-1,2)
Traceback (most recent call last):
File "<pyshell#119>", line 1, in <module>
f.seek(-1,2)
io.UnsupportedOperation: can't do nonzero end-relative seeks
>>> f.seek(1,2)
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
f.seek(1,2)
io.UnsupportedOperation: can't do nonzero end-relative seeks
末尾/whence=2情况,相对位移只能为零。这同样令人感到奇怪,原因会在后面讲。
问题
比较help文档的内容和我们前面所得,我们知道whence=1或2时,表现与预期不相符。这是由于打开方式的问题。以“t”方式(文本模式)打开的文件是无法从当前位置或末尾位置开始计算位移的,只允许从开头位置开始计算位移。注意观察上面代码的异常信息。第一段代码中报ValueError异常,而后面的报io.UnsupportedOperation异常。显然异常不同,造成异常的原因也不同。
想要从当前或末尾位置开始计算位移,应当使用“b”方式(二进制模式)打开文件。
>>> f = open("demo.txt","rb")
>>> f.seek(0)
0
>>> f.seek(-1)
Traceback (most recent call last):
File "<pyshell#106>", line 1, in <module>
f.seek(-1)
OSError: [Errno 22] Invalid argument
>>> f.seek(3)
3
>>> f.seek(0,1)
3
>>> f.seek(-1,1)
2
>>> f.seek(1,1)
3
>>> f.seek(0,2)
10
>>> f.seek(-1,2)
9
>>> f.seek(1,2)
11
Python-基础-文件操作-随机存取的更多相关文章
- python基础-文件操作
一.文件操作 打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作. 打开文件的模式有: r ,只读模式[默认模式,文件必须存在,不存在则抛出异 ...
- python基础-文件操作(10)
一.什么是文件 等等这些都叫做文件,各种格式的.但不仅仅限制于这些. 二.文件的作用 大家应该听说过一句话:“好记性不如烂笔头”. 不仅人的大脑会遗忘事情,计算机也会如此,比如一个程序在运行过程中用了 ...
- Python基础--文件操作和集合
这篇博客来说一下python对文件的操作. 对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句柄操作文件 3.关闭文件. 现有以下文件file.txt: 我们哭了 ...
- python 基础文件操作
实时刷新到硬盘里 f= open('hh','w',encoding='utf8') f.write('gyftyftft') f.write('hghgh\njkkjk') f.flush()#实时 ...
- Python 基础 文件操作
字符串与字节之间的转换 # utf-8 一个汉字 占三个字节 # gbk 一个汉字 占两个字节 # 字符串转换成字节 print(bytes('汉字', encoding='utf-8'))print ...
- python基础--文件操作实现全文或单行替换
python修改文件时,使用w模式会将原本的文件清空/覆盖.可以先用读(r)的方式打开,写到内存中,然后再用写(w)的方式打开. 替换文本中的taste 为 tasting Yesterday whe ...
- Python基础————文件操作
文件操作 4.1 文件基本操作 obj = open('路径',mode='模式',encoding='编码') # 表示要干嘛 读 还是写 obj.write() #写什么内容 obj.read() ...
- Python基础—文件操作(Day8)
一.文件操作参数 1.文件路径 1)绝对路径:从根目录开始一级一级查找直到找到文件. f=open('e:\文件操作笔记.txt',encoding='utf-8',mode='r') content ...
- python基础 — 文件操作
读取键盘输入 Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘.如下: raw_input input raw_input函数 raw_input([prompt]) 函数从 ...
- Python基础-文件操作(七)
一.文件基本操作 1.open 打开模式: w模式 写模式write 文件不存在时会创建文件,如果文件已存在则会清空文件 r模式 读模式read 文件不存在就报错,存在则准备读取文件 a模式 追加模式 ...
随机推荐
- linux服务器上生成CSR和KEY
CSR表示“ 证书签名请求 ”,这个该证书将用于服务器上.一个CSR包含有关您的组织和域名,地方和国家,将包含在证书中的公钥信息. 本文有3个简单的步骤来创建CSR上的Linux系统(证书签名请求). ...
- Laravel中Session的使用
以file为示例 1.Http request session方法$request->session()->put('key1','value1');echo $request->s ...
- URL编码和解码
1. 为什么需要编码 当数据不利于处理.存储的时候,就需要对它们进行编码.如对字符进行编码是因为自然语言中的字符不利于计算机处理和存储.对图片信息.视频信息.声音信息进行压缩.优化,将其“格式化”,是 ...
- .netcore centos配置systemctl自动启动
systemd分两种服务系统和用户服务 对应存储位路径为系统(/usr/lib/systemd/system).用户(/etc/systemd/user/) [Unit] Description=ap ...
- 阿里云安装 fastdfs 总结
还要开放 23000 22122,添加进安全组
- 使用AOP思想封装JDBC
看代码 package learning.aop2; import org.springframework.stereotype.Component; import java.sql.SQLExcep ...
- 8. find
find使用 find命令的主要作用是对树形目录层次结构进行彻底检查. find命令的一般格式: find pathname -expressions find常用表达式 在当前文件夹中找出名 ...
- ClosureTable
1. 查询所有子节点 SELECT `chidren_id` FROM `xi_category4_closure` WHERE `parent_id` = 0 AND `distance` > ...
- k8s集群证书过期(kubeadm 1.10.2 )
1.k8s 集群架构描述 kubeadm v1.10.2创建k8s集群. master节点高可用,三节点(10.18.60.3.10.18.60.4.10.18.60.5). LVS实现master三 ...
- python tarfile模块
TarFile类对于就是tar压缩包实例. 其由member块组成, member块则包括header块和data块. 每个member以TarInfo对象形式描述. 所以TarFile就是TarIn ...