【问题标题】:Python - Loadtext with specific lines for huge filePython - 为大文件加载带有特定行的文本
【发布时间】:2015-12-11 13:52:21
【问题描述】:

我必须在一个巨大的文本文件中获取特定的行。直到现在我尝试如下。我的目标是为特定迭代提取列,这里每 500 行。但是通过继续“readlines”,有时我会因为文件的大小(直到 4Gb)而崩溃。 所以我想找到另一种方法来避免问题......

with open('/test.txt') as f:
    text = f.readlines()


A = ""    
for i in text[3000:3500]:
  A+=i

B=A.splitlines()
listed = []
for i in range(len(B)):
  C=B[i][3:47].split(" ")

  while True:
    try:
      C.remove("")
    except ValueError:
      break
  listed.append(C)

import numpy as np
import matplotlib.pyplot as plt

#print listed
x = np.array(listed, dtype=float)
y = x.astype(np.float)

plt.plot(y[:,1]);plt.ylim(0,5);plt.show()

这篇文章跟随前question

【问题讨论】:

    标签: python text readline


    【解决方案1】:

    如果我理解正确,您希望获得 3000 到 3500 行。您可以这样做:

    import itertools
    with open('test.txt') as f:
        lines = list(itertools.islice(f, 3000, 3500))
    

    【讨论】:

    • 是的,我想要这些行而不打开所有文件!但是我怎么能把你的代码加入我的呢?我不明白输出...对不起
    • @user3601754 将text[3000:3500] 替换为lines 并将我的代码放在顶部而不是with 块。
    • 好的,但我得到“关闭文件的 I/O 操作”
    • 非常感谢,这正是我所期望的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多