V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ThunderEX
V2EX  ›  Python

for line in open(*)里面怎么倒回去读上一行?

  •  
  •   ThunderEX · 2012-12-17 15:36:35 +08:00 · 6602 次点击
    这是一个创建于 4149 天前的主题,其中的信息可能已经有所发展或是发生改变。
    弱智问题一条,for line in open(*)里面一行一行的读文件,但其中突然想临时引用一下前一行的内容,该怎么引用捏?
    13 条回复    1970-01-01 08:00:00 +08:00
    CoX
        1
    CoX  
       2012-12-17 15:39:53 +08:00
    搞个中间变量存一下
    ritksm
        2
    ritksm  
       2012-12-17 15:44:17 +08:00   ❤️ 1
    .seek(tell()-1)?....
    ritksm
        3
    ritksm  
       2012-12-17 15:44:58 +08:00
    不过中间变量好像方便些...
    ritksm
        4
    ritksm  
       2012-12-17 15:46:01 +08:00   ❤️ 1
    不对。。。忽略第一条。。。那个貌似是offset的不是行- -囧
    ThunderEX
        5
    ThunderEX  
    OP
       2012-12-17 15:59:59 +08:00
    @ritksm 送铜币……但是还是好奇有没有直接能引用回去的办法~
    unfurl
        6
    unfurl  
       2012-12-17 16:02:34 +08:00
    for n, line in enumerate(open(file, 'r').readlines())
    likuku
        7
    likuku  
       2012-12-17 16:15:48 +08:00   ❤️ 1
    open()打开的文件对象没找到index属性,但可以转换为list对象后就可以使用index()来获得当前元素对应的index,当然也可以直接使用list[index]来访问当前元素,或者list[index-1]来访问前一个元素.

    line_src = open ("t")
    line_list = line_src.readlines()
    for line in line_list:
    index_currnet_line = line_list.index(line)
    if index_currnet_line > 0:
    last_line = line_list[index_currnet_line-1]
    chemhack
        8
    chemhack  
       2012-12-17 16:21:37 +08:00
    @likuku O(1)的操作活活被你搞成了O(N),内存占用也成了O(N)
    ThunderEX
        9
    ThunderEX  
    OP
       2012-12-17 16:50:40 +08:00
    @likuku 谢~这么看来还是中间变量好了……
    geekard
        10
    geekard  
       2012-12-17 16:54:16 +08:00
    for line in open(*),这里的open()生成的是匿名文件对象,没法直接引用,能获得的就是下一行内容。即使有文件对象f,还需要知道上一行的字符数,这样才能seek()去。
    ivenvd
        11
    ivenvd  
       2012-12-17 17:28:17 +08:00
    记得 open(*) 在这种语境已经返回迭代器而不是文件对象了,所以只能中间变量了吧。
    xuwenbao
        12
    xuwenbao  
       2012-12-18 08:59:33 +08:00
    >>> import linecache
    >>> linecache.getline('/etc/passwd', 4)
    'sys:x:3:3:sys:/dev:/bin/sh\n'
    sykp241095
        13
    sykp241095  
       2012-12-18 17:14:10 +08:00
    请问iterator支持回退么。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3019 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:38 · PVG 21:38 · LAX 06:38 · JFK 09:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.