【问题标题】:linecache.getline and how to loop to the next linelinecache.getline 以及如何循环到下一行
【发布时间】:2013-10-20 00:45:15
【问题描述】:

我有这段代码在循环

file.write('' + linecache.getline('support_files/sub_page_top_links.txt', 1) + '')

它获取文本文件中的第一行,但是,下次脚本循环时我需要它来获取第 2 行,然后下次脚本循环时我需要它来获取第 3 行,等等。我该怎么做这个?

【问题讨论】:

    标签: python loops getline


    【解决方案1】:

    linecache 用于文件中的随机访问行。

    如果你只想遍历文件中的行,你可以使用,

    with open('filename') as f1:
       file.write('' + f1.readline() + '')
    

    【讨论】:

      【解决方案2】:

      你可以保留一个计数器并增加它,所以:

      i = 1
      
      file.write('' + linecache.getline('support_files/sub_page_top_links.txt', i) + '')
      i += 1
      

      那么下一次就会到第2行,以此类推

      但是,如果您想要的是顺序访问,那么 linecache 并不是最好的方法。只需打开文件并对其进行迭代。

      【讨论】:

        猜你喜欢
        • 2019-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-10
        • 2022-08-06
        相关资源
        最近更新 更多