读取文本文件并仅写入包含特定文本的行。

15 浏览
0 Comments

读取文本文件并仅写入包含特定文本的行。

我正在尝试筛选一个大文本文件,只选择包含特定文本的行,并将整行写入一个新的文本文件。这是我写的代码,但它完全清空了目标文本文件,并给出了"Input past end of file"的错误信息。

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\Users\Choti\Desktop\collect\collect.L"
strTemp = "C:\Users\Choti\Desktop\collect\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do Until ts.AtEndOfStream = false
    strLine = ts.ReadLine
    ' 处理 strLine
    if strLine like "tagId" Then
    objOutFile.Write(strLine)
    end if 
    ts.AtEndOfStream = false
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile  

提前感谢您的帮助!

更新:已修正的代码

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\Users\Choti\Desktop\collect\collect.L"
strTemp = "C:\Users\Choti\Desktop\collect\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do While Not ts.AtEndOfStream
    strLine = ts.ReadLine
    if Instr(1, strLine, "tagId") > 0 Then
       objOutFile.WriteLine strLine
    end if
Loop 
objOutFile.Close
ts.Close

0
0 Comments

问题的原因是代码中使用了VBA的语法"Like",而实际上代码是在使用VBScript语言。VBScript语言不支持"Like"操作符,因此在第15行出现了"Sub or Function not defined"的错误。

解决方法是将第15行的代码修改为VBScript支持的语法。可以使用"InStr"函数来判断字符串中是否包含指定的文本。修改后的代码如下:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\Users\Choti\Desktop\collect\collect.L"
strTemp = "C:\Users\Choti\Desktop\collect\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do While Not ts.AtEndOfStream
    strLine = ts.ReadLine
    ' do something with strLine
    If InStr(1, strLine, "tagId") > 0 Then
       objOutFile.WriteLine strLine
    End If 
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile strFile 
objFS.MoveFile strTemp,strFile  

此时,代码中的判断条件已经修改为VBScript语法,可以正确运行。

0