0

我正在使用以下 VBscript 从我的 csv 文件中获取总行数。我需要帮助将返回的行数导出到 csv 中,该 csv 将有两列 Name 和 Count name 可以是任何值,并且计数是返回的计数。

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
myFile = objArgs(0)
Set objFile = objFSO.OpenTextFile(myFile,1)
Do Until objFile.AtEndOfLine
line = objFile.Line
objFile.ReadLine
Loop
WScript.Echo "Line count of", myFile , "is", line

我想调用脚本的方式是:

Cscript 'vbscript_name' file_name_to_count 'custom_name' 'export_count.csv'

谢谢

4

1 回答 1

1

也许我看不到中断在哪里,因为您只需要创建新文件并只写入 2 行,但它会是这样的:

Set objFile = objFSO.OpenTextFile(objArgs(2), 2, True)
objFile.WriteLine "Name,Count"
objFile.WriteLine objArgs(1) & "," & line
objFile.Close

为了变得更加友好,这里是整个交易:

Set objArgs = WScript.Arguments
iLinesCount = FileLinesCount(objArgs(0))
DumpResult objArgs(2), objArgs(1), iLinesCount
WScript.Echo "File: " & objArgs(0) & " has " & iLinesCount & " lines"

Function FileLinesCount(strFileName)
    With CreateObject("Scripting.FileSystemObject")
        With .OpenTextFile(strFileName, 1)
            Do Until .AtEndOfStream
                Call .ReadLine
            Loop
            FileLinesCount = .Line
        End With
    End With
End Function

Sub DumpResult(strFileName, strCustomName, iCount)
    With CreateObject("Scripting.FileSystemObject")
        With .OpenTextFile(strFileName, 2, True)
            .WriteLine "Name,Count"
            .WriteLine strCustomName & "," & iCount
        End With
    End With
End Sub

为您的命令行参数添加错误检查也很好,但我为您完成了这个简单的任务,干杯!

PS 我想您更愿意将计数数据附加到现有文件中,而不是为每个计数的源文件创建新文件。如果是这样,您在功能上的工作很少DumpResult,只需要打开文件进行附加(ForAppending= 8)并添加“标题”(列名),然后才需要(即新创建文件时):

' modified version w`d be:
Sub DumpResult(strFileName, strCustomName, iCount)
    With CreateObject("Scripting.FileSystemObject")
        With .OpenTextFile(strFileName, 8, True)
            If .Line = 1 Then ' new empty file
                .WriteLine "Name,Count" ' add column names
            End If
            .WriteLine strCustomName & "," & iCount
        End With
    End With
End Sub
于 2013-06-09T21:42:57.903 回答