【问题标题】:Iterating through a file by creating list of specific sections [duplicate]通过创建特定部分的列表来遍历文件[重复]
【发布时间】:2015-12-07 17:11:04
【问题描述】:

我是 python 新手,我正在尝试遍历一个列表并将文件中的每 8 行附加到一个列表中。我将附加到这些元素并在新文件上重写此列表。我一直遇到的是从我想要的 txt 文件中获取特定部分。这是我的代码:

tester1=1
tester2=9
for n,line in enumerate(myList):
    if n>(tester1) and n<(tester2):
        tempList.append(line)
        tester1=tester1+8
        tester2=tester2+8

所以我不想要第 0,1 行。但是第 2 到第 8 行。接下来我需要它转到第 9 到第 17 行......等等。当前的代码将我的 txt 文件中的每 8 个元素都提供给我,该文件被制成一个列表。

【问题讨论】:

  • 您是否要以列表列表结尾,例如 [[line2,line3,line4,line5,line6,line7,line8],[line9,line10...]] ?
  • 是的,我正在寻找那个,我在正确的轨道上吗?
  • 排序...所以如果你想要每 8 行,除了省略第 0 行和第 1 行,你会想要第 2-7 行,然后是第 8-15 行,然后是第 16-23 行,对?
  • 这正是我想要的。
  • 对于那个“可能的重复”,它进入了偶数列表,有没有办法将它放入 for 循环并排除第 0 行和第 1 行?

标签: python file enumerate


【解决方案1】:

以最简单的方式,您可以这样做:

with open('path/to/file.txt') as f:
    next(f); next(f)  # skip first two lines
    lst = []
    while True:
        try:
            lst.append([next(f) for _ in range(8)])
        except StopIteration:
            return lst

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多