Subscribe Bookmark RSS Feed

Opening Multiple Files and comparing filenames

engr

Community Trekker

Joined:

Jun 23, 2011

Hi All,

I need to open multiple files from a particular folder (specifically I want to open .csv files only). I also want to extract some information from the filenames of the files being evaluated.

Currently I have this ...

Set Current Directory( "C:\Jan_24th\" );

files = Files in Directory("C:\Jan_24th");

for(i=1, i<= N Items(files), i++,

    Open(

        files,

     .........

1. This can open all the files I have in the folder. But the problem is that it can open any file that I have in my folder not just .csv files.

2. I want to create a textbox in my journal based on what the current file name is :

     For example,     if(files == "Red_color.csv", textbox("Red")<< Journal;);

                             if(files == "Green_color.csv", textbox("Green")<< Journal;);

                             if(files == "Blue_color.csv", textbox("Blue")<< Journal;);

     I cannot get this to work .... Also, there must be an elegant way to do this (#2) instead of using multiple for-loops. I'm not sure if the "substr" command could be used here.

Thanks!

1 ACCEPTED SOLUTION

Accepted Solutions
Solution

I think Ends With() can be used for #1 if the filenames of csv-files always ends with .csv. Regex is more versatile than Substr for #2. An example:

Set Default Directory( "C:\Jan_24th\" );

files = Files In Directory( "C:\Jan_24th\" );

For( i = 1, i <= N Items( files ), i++,

          If( Ends With( files[i], ".csv" ),

                    Open( files[i] );

                    Text Box( Regex( files[i], "(.+?)_", "\1" ) ) << journal; // All text before first "_" in file i's name is journaled

          )

);

3 REPLIES
Solution

I think Ends With() can be used for #1 if the filenames of csv-files always ends with .csv. Regex is more versatile than Substr for #2. An example:

Set Default Directory( "C:\Jan_24th\" );

files = Files In Directory( "C:\Jan_24th\" );

For( i = 1, i <= N Items( files ), i++,

          If( Ends With( files[i], ".csv" ),

                    Open( files[i] );

                    Text Box( Regex( files[i], "(.+?)_", "\1" ) ) << journal; // All text before first "_" in file i's name is journaled

          )

);

engr

Community Trekker

Joined:

Jun 23, 2011

Thank you MS ... it worked like a charm.

Just a newbie question I guess, why did you use the \1 in your regex. Why the need to re-search the (.+?)   ... its not biggie but something that I thought I'd ask.

ms

Super User

Joined:

Jun 23, 2011

The difference is that with the replace string "\1" the function return only what's inside the first parantheses. It would work well also without "\1" but you would in the current example get e.g. "Red_" instead of just "Red".