Re: how to read file line by line?
- To: mathgroup at smc.vnet.net
- Subject: [mg9175] Re: [mg9151] how to read file line by line?
- From: David Withoff <withoff>
- Date: Tue, 21 Oct 1997 02:02:48 -0400
- Sender: owner-wri-mathgroup at wolfram.com
> Assuming input file like that:
> 10 15 30.0
> 10 30 6.0
> 5 30 4.0
> ...........
>
> how can I read it, line by line, and discard lines with '15' as a
> second word?
> I know that I can read the whole file into a big list and then create a
> list of records using Select, but this does not help on large files.
>
> The required approach is to read in only lines satisfying certain
> criteria. --
> charles loboz
> to reply: remove please.no.spam from the address
One general way to do this is to accumulate the result in a linked list:
In[20]:= !!file
10 15 30.0
10 30 6.0
5 30 4.0
5 15 10.0
10 20 12.0
In[20]:= result = link[];
In[21]:= While[Length[data = Read["file", {Number, Number, Number}]] >=
2,
If[data[[2]] =!= 15, result = link[result, data]]
]
In[22]:= Close["file"];
In[23]:= result
Out[23]= link[link[link[link[], {10, 30, 6.}], {5, 30, 4.}], {10, 20,
12.}]
In[24]:= List @@ Flatten[result, Infinity, link]
Out[24]= {{10, 30, 6.}, {5, 30, 4.}, {10, 20, 12.}}
Dave Withoff
Wolfram Research