Click here to Skip to main content
15,890,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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?
Posted

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:
C#
List<int> myLineNumbers = new List<int>{26, 30};    // 0-based line numbers!!!
IEnumerable<string> justMyLines = File.ReadLines("pathFileName").Where((text, lineNum) => myLineNumbers.Contains(lineNum));

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.
 
Share this answer
 
Comments
_Asif_ 10-Mar-14 15:44pm    
Very nice and clean indeed :) +5
Matt T Heffron 10-Mar-14 15:59pm    
OOPS! I didn't notice the "Python" tag. :sigh:
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
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900