How to loop over sub-folders

Problems with syntax of GAMS
Post Reply
jch
User
User
Posts: 3
Joined: 4 months ago

How to loop over sub-folders

Post by jch » 3 months ago

I have a function:

myFunction.gms

Code: Select all

display "%1";
And a main function testFunction.gms to call myFunction.

Code: Select all

$batinclude myFunction.gms abc
$batinclude myFunction.gms 123
How to call myFunction.gms for each sub-folder? For example, I have three sub-folders in RootFolder. How to write gams codes to take one parameter of RootFolder, it will call myFunction.gms 3 times, and each time with one sub-folder name?

RootFolder
│ myFunction.gms
│ testFunction.gms
├───SubFolder1
├───SubFolder2
└───SubFolderA

This is the expected effects, but how to write a gams codes to do it by giving only the "RootFolder", so that it finds all the sub-folders, and call myFunction.gms one by one? Thank you!

Code: Select all

$batinclude myFunction.gms SubFolder1
$batinclude myFunction.gms SubFolder2
$batinclude myFunction.gms SubFolderA
RootFolder.zip
(768 Bytes) Downloaded 43 times

User avatar
bussieck
Moderator
Moderator
Posts: 502
Joined: 4 years ago

Re: How to loop over sub-folders

Post by bussieck » 3 months ago

Embedded Python is your friend:

Code: Select all

$call test -d dir1 || mkdir dir1
$call test -d dir2 || mkdir dir2
$call test -d dir3 || mkdir dir3
$onechoV > listdir.gms
display "%1";
$offecho

$onEmbeddedCode Python:
import os
dirs = [ root for root, dirs, files in os.walk(os.path.normpath(r"%gams.wdir% ".rstrip()), topdown=True) ]
with open('dirs.gms', 'w') as fd:
  for d in dirs[:-1]:
    fd.write('$batInclude listdir.gms ' + os.path.basename(d) + ' // ' + d + '\n')
$offEmbeddedCode
$eolCom //
$include dirs.gms
-Michael

jch
User
User
Posts: 3
Joined: 4 months ago

Re: How to loop over sub-folders

Post by jch » 3 months ago

bussieck, thank you so much!

Post Reply