热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在VB脚本中逐行读取文件?-HowdoIreadafilelinebylineinVBScript?

Ihavethefollowingtoreadafilelinebyline:我有以下内容逐行读取文件:wscript.echoBEGINfilePathWS

I have the following to read a file line by line:

我有以下内容逐行读取文件:

wscript.echo "BEGIN"

filePath = WScript.Arguments(0)
filePath = "C:\Temp\vblist.txt"
Set ObjFso = CreateObject("Scripting.FileSystemObject")
Set ObjFile = ObjFso.OpenTextFile(filePath)
StrData = ObjFile.ReadLine
wscript.echo "END OF FIRST PART"

Do Until StrData = EOF(ObjFile.ReadLine)
    wscript.echo StrData
    StrData = ObjFile.ReadLine
Loop

wscript.echo "END"

The EOF() function doesn't seem to work:

EOF()函数似乎不起作用:

C:\Users\EGr\Documents\Scripts\VB>cscript testloop.vbs ArgVal
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

BEGIN
END OF FIRST PART
C:\Users\EGr\Documents\Scripts\VB\testloop.vbs(11, 1) Microsoft Vbscript runti
me error: Type mismatch: 'EOF'

I haven't programmed in VB before, but I'm trying to figure out loops so that I can modify a VB script I've been handed. I want to read a file line by line, and do something with each line. If I change the Do Until loop to Do Until StrData = EOF, it works but throws an error when it gets to the end of the file:

我以前没有在VB中编程,但我想弄清楚循环,以便我可以修改我已经交过的VB脚本。我想逐行读取文件,并对每一行做一些事情。如果我将Do Until循环更改为Do Until StrData = EOF,它会起作用,但当它到达文件末尾时会抛出错误:

C:\Users\EGr\Documents\Scripts\VB>cscript testloop.vbs ThisRANDOMValue
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

BEGIN
1
END OF FIRST PART
host1
host2
host3
C:\Users\EGr\Documents\Scripts\VB\testloop.vbs(13, 2) Microsoft Vbscript runti
me error: Input past end of file

I feel like there is probably an easy solution, but I haven't been able to find it. I've tried a few other solutions I've found online, but haven't got as close as the above.

我觉得可能有一个简单的解决方案,但我找不到它。我已经尝试了一些我在网上找到的其他解决方案,但还没有上述那么接近。

2 个解决方案

#1


26  

When in doubt, read the documentation:

如有疑问,请阅读文档:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

#2


1  

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

如果像我这样的人正在搜索只读一个特定的行,那么这里只有第18行是代码:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

推荐阅读
author-avatar
许琼博762375
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有