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
 
Addendum:

Of course, you could just as well use the code directly in your "on_click" command.
However, this way you have a modular structure of your code, making it a lot easier to find certain code segments and hence to find and correct errors.

It is (righteously) considered good programming practice to keep such generic functions like "merge all files into one" in separate procedures or functions.
makes it also a lot easier to re-use them later in other programs.
;-)

[blue]Help us, join us, participate
IAHRA - International Alliance of Human Rights Advocates[/blue]
 
VB's functionality can be extended by accessing additional code libraries. Each library requires that your project has a reference to it.

So the comments in my example simply tell you what libraries to which you need to add references.

To do this simply select the Project menu in the IDE, then choose references, then tick both the libraries that the comments mention. And that's it.

BTW, this isn't scripting ...

(the fact that you are not currently aware of library referencing explains why you had problems with both George's - gmmastros - code and the code you say you had been using originally; they both require a reference to the Microsoft Scripting Runtime library)

And here's a more documented version
Code:
[blue][green]'Requires reference to Microsoft Scripting Runtime library
'and Microsoft Shell Controls and Automation library[/green]
Private Const SHCONTF_NONFOLDERS = 64

Private Sub ConcatFiles(strSourceFolder As String, strTargetFile As String, strFilePattern As String)
    Dim myShell As New Shell32.Shell [green]' Shell is a library of methods and properties usually used by Windows Explorer[/green]
    Dim FilteredFiles As Shell32.FolderItems3 [green]' One of several interfaces to a collection of items in a folder. This particular one conatins a method by which we can apply a filter to the enumeration (For Each ...) of the members[/green]
    Dim SourceFile As Shell32.FolderItem [green]' An individual item in a folder (since this is the Shell, the item is not necessarily just a file: could be a folder, a printer for example)[/green]
           
    Set FilteredFiles = myShell.NameSpace(strSourceFolder).Items [green]' OK, get a list of the folder items from the named folder into out FilteredFiles[/green]
    FilteredFiles.Filter SHCONTF_NONFOLDERS, strFilePattern [green]' Set a filter on our list of folder items[/green]
    
    With New FileSystemObject [green]' Ok, let's get a reference to a FileSystemObject which we need for doing out file appending[/green]
        For Each SourceFile In FilteredFiles [green]' for each filtered item - in our case anything that isn't a folder and matches the file pattern we set in strFilePattern ...[/green]
	    [green]' Open our target file in append mode        and write  the entire contents of our source file to it	[/green]	
            .OpenTextFile(strTargetFile, ForAppending, True).Write (.OpenTextFile(SourceFile.Path).ReadAll)
        Next
    End With
End Sub[/blue]
 
Sweet! I have it working perfectly. I used strongm's solution with the help of MakeItSo's posts. I still had an issue with the linebreaks like with the DOS command but I simply added this line to the function:
Code:
.OpenTextFile(strTargetFile, ForAppending, True).WriteLine ("")

This method works like a charm as I am sure the others would have if I was smart enough to figure them out ;)

Anyway, thank you very much for the help everyone you all saved me tons of frustration and head bashing.

Derk
 
I still like my version (since I don't like FSO) and if you don't want to give a FileListBox for your users to see, move it away from the Form or make it .Visib;e = False (you still can use all its functionality) and the rest of the code is very easy to fallow.



Have fun.

---- Andy
 
>but I simply added this line to the function

Or you could simply have extended the core line in my code from
Code:
[blue].OpenTextFile(strTargetFile, ForAppending, True).Write (.OpenTextFile(SourceFile.Path).ReadAll)[/blue]
to
Code:
[blue].OpenTextFile(strTargetFile, ForAppending, True).Write (.OpenTextFile(SourceFile.Path).ReadAll [bold]& vbCrLf[/bold])[/blue]

>since I don't like FSO

I've never really understood the aversion that some people have for the FSO. Sure, it would be nice if it handled reading and writing of file types other than text files (but textstreams are all it is designed to read and write; you wouldn't complain that the textbox is bad because it doesn't handle JPEG conversions properly, for example) - but that's only one of the things FSO does, and people seem to miss out on/ignore all that other functionality because they focus of the FSO as being a tool just for reading and writing text files ...
 
>> all that other functionality

I prefer to use the file system object for all of my text file handling. I also know about the dictionary object even though I have never used it.

What (if any) other gems are hidden in there?

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
>I also know about the dictionary object

Ah, I think you are confusing the Scripting Object library with the FSO (which is just one part of the Scripting library). I'm not talking about all the other bits in the Scripting library, I'm just talking about all the other functionality in the FSO.

Examples (assuming fso is set as a FileSystemObject):

Parsing paths into correct format (in a resilient fashion, and noting that the path doesn't actually have to exist for it to work)

MsgBox fso.GetAbsolutePathName("c:/zxxyz\")

Easily splitting filenames out of full paths (again file and path doesn't actually have to exist, and again it deals with typical path errors):

MsgBox fso.GetFileName("c:\spoonydraw/elephant/myfile.myextension")

Building full file paths, given a filename and a path (without worrying whether the path has a trailing slash or not - see MakeItSo's earlier post where code to handle a trailing slash was introduced)

MsgBox fso.BuildPath("c:/sdrf/drft", "anotherfile.ext")
MsgBox fso.BuildPath("c:/sdrf/drft/", "anotherfile.ext")

Creating unique temporary file names
Determining the file system on any attached drive
Some simple standard stream redirection






 
You're right. I was confused. I know about most of that. I just wanted to make sure I wasn't overlooking something. my favorite is GetExtensionName.

MsgBox fso.GetExtensionName("c:\spoonydraw/elephant/myfile.myextension.[!]txt[/!]")

With this, you don't need to wory about someone creating a file with a dot in the name. You can easily get the file extension without resorting to arrays or the reverse function.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top