user2304104
user2304104

Reputation: 13

Read data from file with certain extension

I am working with a VB script to read data from a text file. It works fine.

My challenge is that the file name changes everyday with date appended to it. The file is a text file and end with .TXT extension. Thus every time I have to rename the file to a fixed name that I have used in my script.

Is there a way to read a file from the current folder and with extension .TXT irespective of the name of the file. In the following code I am reading SNMP.TXT file, but the filename could be SNMP_20130415_xxxx.TXT one day and the SNMP_10130416_xxxx.TXT next day and so on.

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInpoutFile = objFSO.OpenTextFile("D:\scripts\vb\FileHandleScript\SNMP.TXT",1)
Set objOutputFile = objFSO.OpenTextFile("D:\scripts\vb\FileHandleScript\snmp.csv",2,True)

Upvotes: 1

Views: 1479

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

An alternative without regular expression:

For Each f in objFSO.GetFolder("D:\scripts\vb\FileHandleScript").Files
  name = LCase(f.Name)
  If Left(name, 5) = "snmp_" And objFSO.GetExtensionName(name) = "txt" Then
    'do stuff
  End If
Next

Upvotes: 1

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38755

Loop over the files in the folder, use a RegExp to find the file to process, exit the loop after having processed the file:

Dim reFiNa : Set reFiNa = New RegExp
reFiNa.IgnoreCase = True
reFiNa.Pattern = "^snmp_.+\.txt$" ' starting with snmp_, ending with .txt
For Each oFile in objFSO.GetFolder("D:\scripts\vb\FileHandleScript").Files
    If reFiNa.Test(oFile.Name) Then
       ... process file ...
       Exit For
    End If
Next

Upvotes: 1

Related Questions