问题
For some reason when I use the objFile.ReadLine method to read my text file, the entire file is returned as one long line. The file I'm opening is using CR line endings instead of CRLF or LF line endings. Does anyone know how I can read this file line by line in vbscript if ReadLine does not recognize CR line endings? Code is below:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txsInput = objFSO.OpenTextFile("C:\Path\To\My\File.csv",1)
'Read lines one by one
Do While txsInput.AtEndOfStream <> True
strTemp = txsInput.ReadLine
msgbox strTemp
Loop
Instead of alerting for each line, I get one alert with the entire file. Any help is appreciated.
回答1:
.ReadLine
won't work in your case, because it depends on the existence of a vbLf
character. If you don't want to re-encode the line breaks you can do either what Panayot Karabakalov suggested (if the file is large), or read the entire file and split it at vbCr
(if the file is not-so-large):
text = objFSO.OpenTextFile("C:\Path\To\My\File.csv").ReadAll
For Each line In Split(text, vbCr)
MsgBox line
Next
Re-encoding the file can be done like this:
Set fso = CreateObject("Scripting.FileSystemObject")
filename = "C:\path\to\your.csv"
Set infile = fso.OpenTextFile(filename)
Set outfile = fso.OpenTextFile(filename & ".tmp", 2)
Do Until infile.AtEndOfStream
c = infile.Read(1)
If c = vbCr Then
outfile.Write vbCrLf
Else
outfile.Write c
End If
Loop
infile.Close
outfile.Close
fso.DeleteFile filename, True
fso.MoveFile filename & ".tmp", filename
Or you could use something like recode for the conversion. Most text editors (e.g. Vim, Notepad++, SciTE, UltraEdit, …) can do this kind of conversion, too.
回答2:
Maybe not the best idea (and not tested) but try this one.
Do Until txsInput.AtEndOfStream
strTemp = ""
Do
strChar = txsInput.Read(1)
If strChar <> vbCr Then
strTemp = strTemp & strChar
Else
Exit Do
End If
Loop
If Len(strTemp) Then MsgBox strTemp
Loop
来源:https://stackoverflow.com/questions/17180739/vbscript-skipline-and-cr-line-endings