读取文件的特定行 [英] reading specific lines of a file

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

问题描述

大家好,


我想阅读一个巨大的txt文件的特定行(我知道行#)。

每行可能有不同大小。在Python中有这种方便快捷的方法吗?谢谢。


易兴

Hi All,

I want to read specific lines of a huge txt file (I know the line #).
Each line might have different sizes. Is there a convenient and fast
way of doing this in Python? Thanks.

Yi Xing

推荐答案

如果第一行的行号是0:


source = open(''afile.txt'')

for i,line in enumerate(source):

if i == line_num:

break

打印行


Pierre

If the line number of the first line is 0 :

source=open(''afile.txt'')
for i,line in enumerate(source):
if i == line_num:
break
print line

Pierre


>>>>易兴< yx *** @ stanford.edu(YX)写道:
>>>>Yi Xing <yx***@stanford.edu(YX) wrote:

> YXHi All,
YXI想要读取一个巨大的txt文件的特定行(我知道#行)。每个
YXline可能有不同的尺寸。有没有一种方便快捷的方式在Python中使用它?谢谢。
>YXHi All,
YXI want to read specific lines of a huge txt file (I know the line #). Each
YXline might have different sizes. Is there a convenient and fast way of
YXdoing this in Python? Thanks.



不快。你必须阅读所有前面的行。

如果在文件没有改变的情况下你必须多次这样做,你可以

在文件中建立一个索引。 />
-

Piet van Oostrum< pi ** @ cs.uu.nl>

网址: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]

私人电子邮件: pi**@vanoostrum.org

Not fast. You have to read all preceding lines.
If you have to do this many times while the file does not change, you could
build an index into the file.
--
Piet van Oostrum <pi**@cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: pi**@vanoostrum.org



易兴写道:

Yi Xing wrote:

我想读取一个巨大的txt文件的特定行(我知道行#)。

每行可能有不同的大小。在Python中有这种方便快捷的方法吗?谢谢。
I want to read specific lines of a huge txt file (I know the line #).
Each line might have different sizes. Is there a convenient and fast
way of doing this in Python? Thanks.



#!/ usr / bin / env python

import os,sys

line = int(sys.argv [1])

path = sys.argv [2]

os.system(" sed -n%dp%s"%( line,path))

有些人可能会认为这并不是真的在Python中用它做b $ b。事实上,我会争辩说!但是如果

你处于命令提示符并且你想要
见第7358行,那么键入

要容易得多%sed -n 7358p

比编写python单线程更好。

#!/usr/bin/env python

import os,sys
line = int(sys.argv[1])
path = sys.argv[2]
os.system("sed -n %dp %s"%(line,path))
Some might argue that this is not really doing
it in Python. In fact, I would argue that! But if
you''re at a command prompt and you want to
see line 7358, it''s much easier to type
% sed -n 7358p
than it is to write the python one-liner.


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

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