[d]关于文本文件的操作需求

Luffy_龙 2012-09-21 07:10:54
最近在处理文本。
需要增量读取。
比如这次读这个文本到100行
下次直接从100行开始读取
假如保存第100行的内容再正则的话 那就相当于把前100行读取了一遍。。
py不能指定从第100行打开文件么
或者类似linux tail -f的功能

-----------------------------
Double行动:
原帖分数:20
...全文
170 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Luffy_龙 2012-09-25
  • 打赏
  • 举报
回复
3Q 我去试一下
Gloveing 2012-09-21
  • 打赏
  • 举报
回复
seek就是干这个的

file.seek(offset[, whence])
Set the file’s current position, like stdio‘s fseek(). The whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file’s end). There is no return value.

For example, f.seek(2, os.SEEK_CUR) advances the position by two and f.seek(-3, os.SEEK_END) sets the position to the third to last.

Note that if the file is opened for appending (mode 'a' or 'a+'), any seek() operations will be undone at the next write. If the file is only opened for writing in append mode (mode 'a'), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+'). If the file is opened in text mode (without 'b'), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

Note that not all file objects are seekable.

bugs2k 2012-09-21
  • 打赏
  • 举报
回复
采用辅助文件记录上次文件操作结束位置,下次打开文件后,直接 seek 到相应位置,然后 read
qq120848369 2012-09-21
  • 打赏
  • 举报
回复
除非你将文件划分为定长block, 用二进制操作文件.

这样就可以在另外一个文件里记录下一次的起始行了, 直接做seek偏移到指定的block去写.

37,701

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧