在Python中操作文件之seek()方法的使用教程
作者:goldensun 时间:2023-08-01 14:58:01
seek()方法在偏移设定该文件的当前位置。参数是可选的,默认为0,这意味着绝对的文件定位,它的值如果是1,这意味着寻求相对于当前位置,2表示相对于文件的末尾。
没有返回值。需要注意的是,如果该文件被打开或者使用'a'或'A+'追加,任何seek()操作将在下次写撤消。
如果该文件只打开使用“a”的追加模式写,这种方法本质上是一个空操作,但读使能(模式'a+'),它仍然在追加模式打开的文件非常有用。
如果该文件在文本模式下使用“t”,只有tell()返回的偏移开都是合法的。使用其他偏移会导致不确定的行为。
请注意,并非所有的文件对象都是可搜索。
语法
以下是seek()方法的语法:
fileObject.seek(offset[, whence])
参数
offset -- 这是在文件中,读/写指针的位置。
whence -- 这是可选的,默认为0,这意味着绝对的文件定位,其它的值是1,这意味着寻求相对于当前位置,2表示相对于文件的末尾。
返回值
此方法不返回任何值。
例子
下面的例子显示了seek()方法的使用。
#!/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.readline()
print "Read Line: %s" % (line)
# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print "Read Line: %s" % (line)
# Close opend file
fo.close()
当我们运行上面的程序,它会产生以下结果:
Name of the file: foo.txt
Read Line: This is 1st line
Read Line: This
标签:Python
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python分析最近大火的网剧《隐秘的角落》
2023-07-17 07:09:04
![](https://img.aspxhome.com/file/2023/3/131013_0s.jpg)
详解vue项目中调用百度地图API使用方法
2024-05-09 09:38:29
![](https://img.aspxhome.com/file/2023/0/127420_0s.png)
Go语言使用defer+recover解决panic导致程序崩溃的问题
2024-01-30 06:29:18
![](https://img.aspxhome.com/file/2023/5/105125_0s.png)
JavaScript组件打包模式
2010-04-08 16:26:00
详解go中panic源码解读
2024-03-22 08:22:51
防止web项目中的SQL注入
2024-01-26 00:44:25
Python CSV模块使用实例
2022-02-04 18:56:36
PHP中的一些常用函数收集
2023-10-09 02:06:06
python控制nao机器人身体动作实例详解
2023-08-26 11:33:17
flask循环导入的问题解决
2023-10-01 10:28:52
[教程]用代码让你了解网页与键盘
2008-06-10 12:18:00
jQuery使用手册--核心篇(Core)
2007-11-22 22:05:00
python实现简单颜色识别程序
2022-07-15 09:34:47
![](https://img.aspxhome.com/file/2023/4/121094_0s.jpg)
python 代码运行时间获取方式详解
2021-01-22 19:07:36
初瞥 Google Chrome Frame
2009-10-06 14:41:00
![](https://img.aspxhome.com/file/UploadPic/200910/6/medium-75s.jpg)
用python实现打砖块小游戏
2021-11-10 02:52:06
![](https://img.aspxhome.com/file/2023/6/83716_0s.jpg)
深入分析SQL Server 存储过程
2024-01-19 21:18:09
详解Mysql中的JSON系列操作函数
2024-01-20 02:08:08
![](https://img.aspxhome.com/file/2023/9/107419_0s.png)
七种Python代码审查工具推荐
2021-06-16 07:07:34
asp获取完整url地址代码
2010-03-22 14:25:00