用VBS每行读取一个txt文件 [英] Read line per line a txt file with VBS

查看:54
本文介绍了用VBS每行读取一个txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试此代码:

filename = "test.txt"
listFile  = fso.OpenTextFile(filename).ReadAll
listLines = Split(listFile, vbCrLf)
For Each line In listLines
   WScript.Echo line 
   'My Stuff
Next

或者其他:

filename = "test.txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(filename, ForReading)
    Do Until f.AtEndOfStream
      myLine = f.ReadLine
      WScript.Echo myLine
      'My Stuff
    Loop

为什么在这两种情况下它一次回显所有行,当然我无法逐行工作?有什么想法吗?

Why in both cases it echoes all lines at once, and of course I'm unable to work line by line? Any idea?

推荐答案

你的文件有有趣的 EndOfLine 标记.让我们假设这些行以 vbLf 结尾:

Your file has funny EndOfLine markers. Let's assume the lines are terminated by vbLf:

>> fn = "lf.txt"
>> goFS.CreateTextFile(fn).Write Replace("a b c ", " ", vbLf)
>> set ts = goFS.OpenTextFile(fn)
>> do until ts.AtEndOfStream
>>    WScript.Echo ts.ReadLine
>> loop
>>
a
b
c

如你所见,.ReadLine 可以处理 vbLf (unix).但是,您在 .ReadAll() 上的 Split() 将失败:

As you can see, .ReadLine can cope with vbLf (unix). Your Split() on .ReadAll(), however, will fail:

>> t = goFS.OpenTextFile(fn).ReadAll()
>> a = Split(t, vbCrLf)
>> WScript.Echo UBound(a)
>> WScript.Echo a(0)
>>
0
a
b
c

t 不包含单个 vbCrLf,因此 Split() 返回一个 UBound() == 0 的数组,其中包含 t 作为其单个元素..Echoing 至少看起来像 3 (4) 行.如果您确实需要一系列行,您可以在 vbLf 上使用 Split().

t does not contain a single vbCrLf, so Split() returns an array with UBound() == 0, containing t as its single element. .Echoing that will at least look like 3 (4) lines. You could Split() on vbLf, if you really need an array of lines.

但是如果您的文件包含 vbLf 结尾,那么 .ReadLine 循环应该可以正常工作.

.ReadLine() 无法处理 vbCr (mac):

.ReadLine() can't cope with vbCr (mac):

>> fn = "cr.txt"
>> goFS.CreateTextFile(fn).Write Replace("a b c ", " ", vbCr)
>>
>> set ts = goFS.OpenTextFile(fn)
>> do until ts.AtEndOfStream
>>    WScript.Echo ts.ReadLine
>> loop
>>
c

b+cr '覆盖' a+cr,然后被 c+cr '覆盖'..ReadAll() 方法也会失败,除非您使用 vbCr 作为分隔符.

The b+cr 'overwrites' the a+cr and is then 'overwritten' by c+cr. The .ReadAll() approach will fail too, unless you use vbCr as separator.

但是,如果您的文件包含 vbCr 结尾,那么您的任何片段都不能一次回显所有行".

你的文件来自外太空吗?

Does your file come from outer space?

更新评论:

您不能使用文件系统对象读取 UTF-8.将文件转换为 UTF-16 并在 .OpenTextFile 时使用格式参数的 Unicode 选项,或者使用 ADODB 流.

You can't read UTF-8 using the Filesystemobject. Either convert the file to UTF-16 and use the Unicode option of the format parameter when .OpenTextFile it, or work with an ADODB Stream.

了解使用什么 EOL 标记仍然很有趣.

It still would be interesting to know what EOL marker is used.

这篇关于用VBS每行读取一个txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆