【问题标题】:Python - read 1000 lines from a file at a timePython - 一次从文件中读取 1000 行
【发布时间】:2017-06-15 16:24:02
【问题描述】:

我检查过thisthisthis

第三个链接似乎有答案,但它没有完成工作。

我无法找到将整个文件放入主内存的解决方案,因为我要处理的文件会非常大。所以我决定使用islice,如第三个链接所示。前 2 个链接无关紧要,因为它们仅用于 2 行或读取 1000 个字符。而我需要 1000 行。 for now N is 1000

我的文件包含 100 万 行:

示例:

1 1 1
1 2 1
1 3 1
1 4 1
1 5 1
1 6 1
1 7 1
1 8 1
1 9 1
1 10 1

因此,如果我一次阅读 1000 行,我应该通过 while 1000 次,但是当我打印 p 以检查我已经通过了多少次时,它不会停止在1000。在运行我的程序1400 秒后,它达到了19038838!!

代码:

def _parse(pathToFile, N, alg):
    p = 1
    with open(pathToFile) as f:
        while True:
            myList = []
            next_N_lines = islice(f, N)
            if not next_N_lines:
                break
            for line in next_N_lines:
                s = line.split()
                x, y, w = [int(v) for v in s]
                obj = CoresetPoint(x, y)
                Wobj = CoresetWeightedPoint(obj, w)
                myList.append(Wobj)
            a = CoresetPoints(myList)
            client.compressPoints(a) // This line is not the problem
            print(p)
            p = p+1
    c = client.getTotalCoreset()
    return c

我做错了什么?

【问题讨论】:

  • f 可能没有被消耗,因此您最终每次都读取相同和相同的 1000 行。这永远不会终止。您必须使用 islice 的替代公式(itertools.islice(iterable, start, stop[, step]) 这个而不是 itertools.islice(iterable, stop) 这个)

标签: python python-2.7


【解决方案1】:

正如@Ev.kounis 所说,您的 while 循环似乎无法正常工作。

我会建议像这样一次为大块数据使用 yield 函数:

def get_line():
    with open('your file') as file:
        for i in file:
            yield i

lines_required = 1000
gen = get_line()
chunk = [next(gen) for i in range(lines_required)]

【讨论】:

  • 但它不会尝试为每一行打开同一个文件1M 次吗?它会减慢程序的速度,不是吗?
  • 不,它只会重复for循环中的步骤。 Yield 可以解释为“返回此输入并在被要求时准确地返回此处”。查看生成器的文档:docs.python.org/3/howto/functional.html#generators
  • @MKesper 如果文件结束了怎么办,这样我就可以停止迭代和阅读? if not chunk: break 没用。有什么想法吗?
  • 设法通过用try 包装它来解决这个问题,如果抛出异常,那么我会中断。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 2012-12-31
相关资源
最近更新 更多