特定行数的Loadtext [英] Loadtext for specific number of lines

查看:68
本文介绍了特定行数的Loadtext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要加载的文件很大,所以无法直接打开它.我想我必须分多个部分阅读它.

I have a huge file to load so I can't open it directly. I think I have to read it in multiple parts.

例如,为了使用第1到50行,我尝试了类似的方法,但是它不起作用:

For instance, in order to use lines 1 to 50, I tried with something like that, but it doesn't work:

import numpy as np

with open('test.txt') as f:
    lines = (line for line in f if line < 50.)
    FH = np.loadtxt(lines, delimiter=',', skiprows=1)

推荐答案

在Python 3中,请尝试以下操作:

In Python 3, please try this:

a = 0
f = open('test.txt')
while a < 50:
    a = a + 1
    print(f.readline(), end='')
else:
    f.close()

在Python 2中,使用此命令:

In Python 2, use this:

a = 0
f = open('test.txt')
while a < 50:
    a = a + 1
    print f.readline(),
else:
    f.close()


或选择这种方式,请使用readlines():

or choose this way, use readlines():

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

readlines()将创建一个列表,并且一行是一个对象.因此,如果您需要20到50行,可以执行以下操作:

readlines() will create a list, and one line is one object. so if you want the 20 - 50 lines, you can do this:

for i in text[20:50]:
    print(i)

这篇关于特定行数的Loadtext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆