「python」文件的随机读写
2017-09-06 07:29
295 查看
文件的随机读写
获取当前读写的位置
在读写文件的过程中,如果想知道当前的位置,可以使用tell()来获取# 打开一个已经存在的文件 f = open("test.txt", "r") str = f.read(3) print "读取的数据是 : ", str # 查找当前位置 position = f.tell() print "当前文件位置 : ", position str = f.read(3) print "读取的数据是 : ", str # 查找当前位置 position = f.tell() print "当前文件位置 : ", position f.close()
定位到某个位置
如果在读写文件的过程中,需要从另外一个位置进行操作的话,可以使用seek()seek(offset, from)有2个参数
offset:偏移量
from:方向
0:表示文件开头
1:表示当前位置
2:表示文件末尾
demo:把位置设置为:从文件开头,偏移5个字节
# 打开一个已经存在的文件 f = open("test.txt", "r") str = f.read(30) print "读取的数据是 : ", str # 查找当前位置 position = f.tell() print "当前文件位置 : ", position # 重新设置位置 f.seek(5,0) # 查找当前位置 position = f.tell() print "当前文件位置 : ", position f.close()
demo:把位置设置为:离文件末尾,3字节处
# 打开一个已经存在的文件 f = open("test.txt", "r") # 查找当前位置 position = f.tell() print "当前文件位置 : ", position # 重新设置位置 f.seek(-3,2) # 读取到的数据为:文件最后3个字节数据 str = f.read() print "读取的数据是 : ", str f.close()
相关文章推荐
- python文件随机读写例子
- python读写文件
- Python 文件读写
- 第34课 Python列表与文件读写
- 读写随机访问文件
- Learn Python The Hard Way学习(16) - 读写文件
- 【python学习笔记】22:numpy文件读写和一些常量
- python中文件读写
- Python文件操作读写文件
- Python:file/file-like对象方法详解【单个文件读写】
- python 文件读写操作
- python 读写文件和设置文件的字符编码
- Python 文件读写操作实例详解
- Python 文件读写操作实例详解
- Python读写文件
- 文件随机读写实现...fseek
- Python读写,以及修改my.ini文件--针对Python3.0版本
- Python实现读写文件
- 【引用】Python open读写文件实现脚本
- python 笔记 之 文件读写