# How many records? In a file (streaming)

I want to know how many records a file (large data) contains... with streaming...like this:

str = OpenRead[
"https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2015-08.csv"
]



but nothing happens...

• Maybe use Length instead of Count? Or Count[bla, _]? Still, Read[str, {Word, Number}] is not what you think it is... – Henrik Schumacher Mar 1 '18 at 10:19
• @HenrikSchumachert thank you... Length still doesn't work though – Cécile Meier Mar 1 '18 at 10:27

Something like

str = OpenRead["https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2015-08.csv"]
Close[str];
Length[records]


would do it but that would imply that the whole file gets downloaded...

Alternatively, you can use

str = OpenRead["https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2015-08.csv"]
c = 0;
Dynamic[c]
record = "";
While[record =!= EndOfFile,
c++;
];
Close[str]


This also loads the whole file, but it keeps only one record in memory. Better use that only for files on your local drive.

A recursive variant could look like this (first an example data set)

Export["a.csv", StringSplit[ExampleData[{"Text", "FaustI"}]]];

countRecords[url_String] := Block[{f, \$IterationLimit = \[Infinity]},

f[str_, EndOfFile, c_] := c;
f[str_, record_, c_] := f[str, Read[str, {Record}], c + 1];

InternalWithLocalSettings[
Null
,
,
Close[str];
]
]
]


I use InternalWithLocalSettings in order to have the stream closed even if the user aborts the execution.

Here a usage example:

countRecords["a.csv"]


30620

• Is there a functional version of this, eg avoiding the internal increment c++, that looks a lot like the 1970s. – alancalvitti Mar 1 '18 at 17:07
• @alancalvitti Feel free to wrap a function around it yourself. – Henrik Schumacher Mar 1 '18 at 18:15
• nope, I mean a functional alternative to the procedural method, with no iterators, only Map, Apply, recursion, etc. – alancalvitti Mar 1 '18 at 18:19
• @alancalvitti Recursion will likely hit the recursion limit and there is no list to Map on; actually, one does not want to have a list in memory here since the data in the file is huge. The point of handling streams lies within the fact that one wants to operate only on the current part of the stream. – Henrik Schumacher Mar 1 '18 at 18:25
• @alancalvitti It's just ridiculous to try to avoid any plus operations in the code. Recall: We have to count here something. – Henrik Schumacher Mar 3 '18 at 9:57