Click to See Complete Forum and Search --> : Converting a text file into a CSV File
gknierim
February 15th, 2000, 10:03 AM
I have opened a text file for input. But before I can process my loop, I have already reached the EOF. Why is this and how do I set it back to the beginning? Below is the code I am using:
Function FileToCSV(sFile as string, sCsv as string)
Dim buffer as string
Open sFile for input as #1
Open sCsv for Output as #2
Do While Not EOF(1)
Line input #1, buffer
print #2, buffer & ","
Loop
Close #1
Close #2
End Function
As you can tell, I'm trying to convert a textfile into a CSV file.
I've searched for some examples and can't find any. I would love any suggestions either for the EOF fix or example code for converting a text file into a CSV file.
Thanks,
Greg
Kyle Burns
February 15th, 2000, 10:37 AM
If you're using VB6, The FileSystemObject is much easier to deal with than the old "open as, input" method.
Try something like this:
Function FileToCSV(sFile as string, sCSV as string)
'Need to add error checking
Dim oFS as Scripting.FileSystemObject
Dim oStreamIn as Scripting.TextStream
Dim oStreamOut as Scripting.TextStream
set oFS = new Scripting.FileSystemObject
set oStreamIn = oFS.OpenTextFile(sFile)
set oStreamOut = oFS.CreateTextFile(sCsv)
Do Until oStreamIn.AtEndOfStream
oStreamOut.Write oStreamIn.ReadLine() & ","
Loop
oStreamIn.Close
oStreamOut.Close
set oStreamIn = nothing
set oStreamOut = nothing
set oFS = nothing
End Function
gknierim
February 15th, 2000, 11:10 AM
Ok, I put in the FileSystemObject code but I am still having the same problem with oStreamIn.AtEndOfStream being true and never executing the Do Loop. How do I set it to false but more importantly why is it already true?
Kyle Burns
February 15th, 2000, 11:52 AM
What is the content of the file?
gknierim
February 15th, 2000, 12:04 PM
It has 144 lines of text in it. Basically the text file has an entry on each line. All I want to do is read the first line, insert the whole line into a field into a DB, read the next line, insert, and so on. There is text in the file.
Kyle Burns
February 15th, 2000, 01:08 PM
It almost sounds like you aren't pointing to the file that you think you are. If you're not specifying the full path to the file, try that. Another thought would be to leave the loop out and try Debug.print oInputStream.ReadAll()
gknierim
February 15th, 2000, 01:34 PM
Yea, I figured it wasn't pointing correctly. I forgot to specify the path. Duh me! Thanks for you help. In the meantime though I finally did find 2 examples of coverting txt to csv files using the old method with only a couple lines of code. They can checked out at
http://www.planet-source-code.com
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.