如何使用vbscript从文本文件中读取每20行?

时间:2016-07-20 09:55:54

标签: vbscript

我在文本文件中有180行,并希望每20行读取一次(1-20,21-40 ......)

这是我目前的代码:

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objTextFile = objFSO.OpenTextFile("C:\Bess_Automation\EditFiles\TSTVLD1.txt", ForReading)

'Reading the count of lines
objTextFile.ReadAll
strLinecount=objTextFile.Line
msgbox strLinecount

strnumoftimes=Round((strLinecount/20),0)
msgbox strnumoftimes

1 个答案:

答案 0 :(得分:3)

以下是我如何解决问题的方法。此代码最初设置一次读取的行数,然后打开文件进行读取并设置数组。虽然我们还没有完成阅读文件,但我们会在其中添加一行myArray

当我们达到读取的20行的倍数时,我们报告并执行我们需要的20行(在我的情况下,我只是将它们回显到屏幕上,用分号分隔)。

然后我们重新将数组重置为空并重复直到所有文件都被读取,然后输出最后一批行(否则它们将被忽略,因为我们只对20个批次中的任何一个做例子)。

Option Explicit

Const LINES_TO_READ = 20
Dim iLines, iTotalLines
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFile : Set oFile = oFso.OpenTextFile("C:\temp\mytextfile.txt", 1)
Dim myArray()
ReDim myArray(0)
iLines = 0
iTotalLines = 0
While Not oFile.AtEndOfStream
    myArray(UBound(myArray)) = oFile.ReadLine
    iLines = iLines + 1
    ReDim Preserve myArray(UBound(myArray)+1)
    If iLines Mod LINES_TO_READ = 0 Then
        WScript.Echo iLines & " read now."
        ' do anything you like with the elements of myArray here before we reset it to empty
        WScript.Echo Join(myArray, ";")
        ' reset array to be totally empty again
        ReDim myArray(0)
    End If
Wend
WScript.Echo "Final Lines: " & Join(myArray, ";")
WScript.Echo "Total lines in file: " & iLines