Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading Multiple Text Files 1

Status
Not open for further replies.

Derkus

Technical User
May 30, 2007
11
US
Hello Everyone, I am new around here and have run into a slight scripting problem.

I am writing a small app that will look in a folder, read all the text files in the folder, and write their contents into a new file. I have most of the code worked out but am having trouble getting it to read more than one file.

The Basic Flow of my program is to validate all the folders used, create the empty text file for writing, then (the plan is) loop through each text file in the source folder reading it and writing the contents to the new file.

Can anyone give me some pointers on how to read more than one file?

Any help would be greatly appreciatted. Thanks.

Derkus
 
Hi and welcome to Tek-Tips. Read faq222-2244 to see how to get the best from these forums.

For this question the easy way is to use the Dir function in a loop. VBHelp gives details

___________________________________________________________
If you want the best response to a question, please check out FAQ222-2244 first.
'If we're supposed to work in Hex, why have we only got A fingers?'
Drive a Steam Roller
Steam Engine Prints
 
Thanks for the tips John.

I think perhaps I should be a bit more clear on the issue. Here is the relevant code I currently have. It won't hurt my feelings if someone has a better way to go about this.


For Each [red]Not sure what goes here[/red]
'Get Data From File
Const ForReading = 1
Set objCurrentFile = filesys.OpenTextFile([red]Not sure how to designate current loop position here[/red], ForReading)
strContents = objFile.ReadAll
objFile.Close
'Append Data to File
Const ForAppending = 8
Set objFile = filesys.OpenTextFile(objFullPath, ForAppending, True)
objFile.WriteLine ("")
objFile.Write strContents
objFile.Close
Next
 
It may be too much, but the way I do it:
I have on my Form: a DriveListBox to pick my drive, DirListBox to see the folders in a chosen drive, and a FileListBox to see/filter files from the chosen folder.

Then I can do that:
Code:
Dim strLine As String
Dim f As Integer

Open App.Path & "\MyNewTextFile.txt" For Output As #2

For f = 0 To FileListBox.ListCount - 1
    FileListBox.ListIndex = f
    Open FileListBox.Path & "\" & FileListBox.List(f) For Input As #1
    Do While Not EOF(1)
        Line Input #1, strLine
        Print #2, strLine
    Loop
    Close #1
Next f

Close #2
You may want to use FreeFile instead of #1 or #2

Have fun.

---- Andy
 
Thank you for the response Andy. This looks very much like what I need. Your solution uses a listbox to create the file list. In my instance I would prefer not to have a listbox in the user interface. Is there a way I can use a variable or some such to serve the same function?
 
As johnwm suggested, look up Dir in Help:
Code:
[b]Dir[/b]
[green]'Returns filename with specified extension. 
' If more than one *.txt
' file exists, the first file found is returned.[/green]
MyFile = Dir("C:\SomeFolder\*.txt")

[green]' Call Dir again without arguments to return 
' the next *.txt file in the same directory.[/green]
MyFile = Dir

HTH


Have fun.

---- Andy
 
Code:
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File

Set oFolder = filesys.GetFolder("C:\")

For Each oFile In oFolder.Files 
        'Get Data From File
        Const ForReading = 1
        Set objCurrentFile = filesys.OpenTextFile(oFile.Path, ForReading)
        strContents = objFile.ReadAll
        objFile.Close
        'Append Data to File
        Const ForAppending = 8
        Set objFile = filesys.OpenTextFile(objFullPath, ForAppending, True)
        objFile.WriteLine ("")
        objFile.Write strContents
        objFile.Close
Next

I think you have other problems with this code, but I'll leave it up to you to find them.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Thanks again guys.

George, this method you posted is something I tried before posting for some help. The problem I am running into is that I get an error when running it: "Compile Error: User defined Type not Defined"

It seems to me that this is the way to go but I haven't figured out how to get around this error.

As to other problems with the code I am sure it is not a masterpeice by any means, I am just a beginner at this and just want to make it work. I'll clean things up later.
 
Oops, ment to say that it throws that error at this line:

Code:
Dim oFolder As Scripting.Folder
 
Here's yet another illustrative alternative:

Code:
[blue][green]'Requires reference to Microsoft Scripting Runtime library
'and Microsoft Shell Controls and Automation library[/green]
Private Sub ConcatFiles(strSourceFolder As String, strTargetFile As String, strFilePattern As String)
    Dim myShell As New Shell32.Shell
    Dim FilteredFiles As Shell32.FolderItems3
    Dim SourceFile As Shell32.FolderItem
           
    Set FilteredFiles = myShell.NameSpace(strSourceFolder).Items
    FilteredFiles.Filter SHCONTF_NONFOLDERS, strFilePattern
    
    With New FileSystemObject
        For Each SourceFile In FilteredFiles
            .OpenTextFile(strTargetFile, ForAppending, True).Write (.OpenTextFile(SourceFile.Path).ReadAll)
        Next
    End With

End Sub[/blue]
 
Yes Andy that would do the job exactly... except it wouldnt have a windows interface. DOS was my first plan when I heard what was needed... then someone came up with the bright idea to make a VB app. That's when all the trouble started.

I am still struggling to get these methods to work for me but thanks a lot for all the help.

Derkus
 
In that case, you can use the VB app as a visual explorer to browse to the folder and then use the folder info to run the dos command in that folder:
Let's say you have a DIR list box and a File list box, right?

e.g.
Code:
Dim PathStr as String, sCommand as String
...
PathStr=Dir1.Path & "\"
sCommand="copy " & pathstr & "*.txt " & pathstr & "AllFiles.txt"
Shell "cmd.exe /c" & sCommand

Not the most elegant thing to first programm a vb app and then use DOS anyway, but it should save you some nerves...
:p

Cheers,
Andy

[blue]Help us, join us, participate
IAHRA - International Alliance of Human Rights Advocates[/blue]
 
Haha! I like the way you think Andy. I think I'll do that. I have a pile of code checking that the paths are all correct, then do a DOS command as a finally. Brilliant!

The only peice I am missing to make it work is that I currently have the path to the files entered in a textbox. What sort of variable do I need to use to make that work with '.Path'?

 
No problemo.
If the path is entered into a textbox, you simply use
Code:
pathstr=TextBox1[b].Text[/b]
if right(pathstr,1)<>"\" then pathstr=pathstr & "\"
The latter part is simply to make sure the pathstr variable finishes with a backslash...
;-)

[blue]Help us, join us, participate
IAHRA - International Alliance of Human Rights Advocates[/blue]
 
Sorry, forgot the following definition in my post:

Private Const SHCONTF_NONFOLDERS = 64
 
Andy, I have this working now though I have run into a problem in that the copy comand does not insert a line break between the files so I end up with lines running together. This is obviously a DOS issue and not a VB one. I can't think of a way for DOS to break these appart without doing each file individually... which of course puts me back to my original issue... cycling through files.

Thanks again for the help.
 
Argh, bummer!

In that case I think you are truly best served with strongm's proposal, including his correction a few posts later, which would then be
Code:
'Requires reference to Microsoft Scripting Runtime library
'and Microsoft Shell Controls and Automation library
Private Const SHCONTF_NONFOLDERS = 64

Private Sub ConcatFiles(strSourceFolder As String, strTargetFile As String, strFilePattern As String)
    Dim myShell As New Shell32.Shell
    Dim FilteredFiles As Shell32.FolderItems3
    Dim SourceFile As Shell32.FolderItem
           
    Set FilteredFiles = myShell.NameSpace(strSourceFolder).Items
    FilteredFiles.Filter SHCONTF_NONFOLDERS, strFilePattern
    
    With New FileSystemObject
        For Each SourceFile In FilteredFiles
            .OpenTextFile(strTargetFile, ForAppending, True).Write (.OpenTextFile(SourceFile.Path).ReadAll)
        Next
    End With

End Sub

And call this code from your Commandbutton CLick event
Code:
ConcatFiles Text1.Text, strpath & "AllFiles.txt", "*.txt"


[blue]Help us, join us, participate
IAHRA - International Alliance of Human Rights Advocates[/blue]
 
Okay, I see that this solution creates a custom function but beyond that it is way over my head. Are the comments at the top comments on what the script is doing, or noting what else needs to be done? Sorry I am a bit slow with scripting methods.
 
They are comments telling you, that in VB, you should click the menu item
"Project->References",
scroll to the items "Microsoft Scripting Runtime" and "Microsoft Shell Controls and Automation" and activate both (tick the check boxes).

This will enable you to use the functions stored in these libraries.
If you do not add these references, you get an error saying "user defined function not set" or the like...
[pipe]

[blue]Help us, join us, participate
IAHRA - International Alliance of Human Rights Advocates[/blue]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top