【问题标题】:how to number lines of txt file in python?如何在python中对txt文件的行数进行编号?
【发布时间】:2014-04-01 18:08:52
【问题描述】:

我想分析 txt.file 的特定部分(第 48-392 行),但我在为 txt 文件的单行编号时遇到问题。 到目前为止,这是我能想到的:

with open ('kafka_hungerkuenstler.txt', encoding = 'utf-8') as f:
    for line in f:
    #I tried: enumerate (line)
    #there should also be something like read_selected_lines (filename, 48,392) somewhere in
     the code      
        print (line) 

【问题讨论】:

  • 是第49行(从0算起)还是第48行(从1算起)?
  • 这是从 1 算起的第 48 行
  • for line in f.readlines()[47:392]:替换for line in f:

标签: python python-3.x enumerated-types


【解决方案1】:

使用itertools.islice() 选择一定范围的行:

from itertools import islice

with open ('kafka_hungerkuenstler.txt', encoding = 'utf-8') as f:
    for line in islice(f, 47, 392):

循环只会遍历第 47 行(从零开始计数)直到第 391 行(含);从 1 开始计数,即第 48 行到第 392 行(含)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2022-01-13
    • 2014-01-06
    • 2020-03-07
    • 2021-12-16
    • 2018-07-25
    • 1970-01-01
    相关资源
    最近更新 更多