Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

vbscript - Read line per line a txt file with VBS

I'm trying this code:

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

Or this other:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 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.

But if your files contains vbLf endings, then the .ReadLine loop should work fine.

.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

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.

But if your files contains vbCr endings, then none of your snippets can "echoe(s) all lines at once".

Does your file come from outer space?

Update wrt comment:

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...