Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to count number of lines in a text file

Need a function that will accept a filename as parameter and then return the number of lines in that file.

Should be take under 30 seconds to get the count of a 10 million line file.

Currently have something along the lines of - but it is too slow with large files:

Dim objFSO, strTextFile, strData, arrLines, LineCount
CONST ForReading = 1

'name of the text file
strTextFile = "sample.txt"

'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll

'Split by lines, put into an array
arrLines = Split(strData,vbCrLf)

'Use UBound to count the lines
LineCount = UBound(arrLines) + 1

wscript.echo LineCount

'Cleanup
Set objFSO = Nothing
like image 861
toop Avatar asked Sep 14 '11 12:09

toop


People also ask

How do you count the number of lines in a text file in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.


1 Answers

If somebody still looking for faster way, here is the code:

Const ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject") 
Set theFile = fso.OpenTextFile("C:\textfile.txt", ForAppending, Create:=True) 
WScript.Echo theFile.Line 
Set Fso = Nothing

Of course, the processing time depend very much of the file size, not only of the lines number. Compared with the RegEx method TextStream.Line property is at least 3 times quicker.

like image 99
k.move Avatar answered Oct 31 '22 15:10

k.move