我正在使用for循环来读取文件,但我只想读取python中的特定行 [英] I'm using a for loop to read a file, but I only want to read specific lines in python
本文介绍了我正在使用for循环来读取文件,但我只想读取python中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用for循环来读取文件,但我只想读取特定行,比如第26行和第30行。是否有任何内置功能来实现这一目标?
I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?
推荐答案
就像谢尔盖所说,你必须阅读所有的内容,至少在你读完之前你想要什么。
然而,你可以使用Linq让它变得非常简单:
Like Sergey said, you'll have to read all of the lines, at least until you've read what you wanted.
However, you can use Linq to make it pretty easy:
List<int> myLineNumbers = new List<int>{26, 30}; // 0-based line numbers!!!
IEnumerable<string> justMyLines = File.ReadLines("pathFileName").Where((text, lineNum) => myLineNumbers.Contains(lineNum));
如果 myLineNumbers
,然后,而不是 List< int>
,使用 HashSet< int>
或 BitArray
会更有效。
If you have a large number of values in myLineNumbers
, then, instead of List<int>
, using a HashSet<int>
or BitArray
would be more efficient.
不幸的是,你仍然需要读取所有行,至少到你提取的位置你需要的信息。
原因很简单:所有行的长度可以不同,它们由行尾定义文件内容中的字符。在读取行至少一次之前,您不知道行结束在文件中的位置。
另请参阅: http://en.wikipedia .org / wiki /行尾 [ ^ ]。
-SA
Unfortunately, you still have to read all lines, at least to the point where you extract the piece of information you need.
The reason for that is very simple: the lengths of all lines can be different, they are defined by the end-of-line characters in the content of your file. Before you read the lines at least once, you don't know where the line ends are located in your file.
See also: http://en.wikipedia.org/wiki/End-of-line[^].
—SA
这篇关于我正在使用for循环来读取文件,但我只想读取python中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文