Read filenames in a directory

28 views
Skip to first unread message

ivanova...@gmail.com

unread,
Oct 23, 2020, 1:41:12 PM10/23/20
to AMPL Modeling Language

Dear smart people,

I need to read data from  uniformatted text files in one folder.
Every time I load data from one text file, I need to solve a model with the data.
The text files in the folder have inconsistent names, say
file1.txt
hypercube43
input.txt
...
I would like to somehow load the filenames into a set of strings, and process them by iterating over this set of strings.
Is there a way how to do it?

Thanks a lot in advance,
Marika

AMPL Google Group

unread,
Oct 24, 2020, 9:59:03 AM10/24/20
to AMPL Modeling Language
Here's a simple example:

set filenames = {"file1.txt","hypercube43","input.txt"};

param n integer > 0;
param a {1..n} >= 0;

for {f in filenames} {
   reset data;
   read n <(f);
   read {j in 1..n} a[j] <(f);
   display a;
}

If the filenames are going to change frequently, then instead of giving their names in the model, you could read the members of set "filenames" from a file, too -- either in AMPL text file format (using "data") or unformatted text (using "read").

(If every file contains the same number of data values, then for this example you don't need the "reset data;" and "read n <(f);" inside the loop.)


--
Robert Fourer
am...@googlegroups.com
{#HS:1318256689-91458#}
file1.txt
hypercube43
input.txt
readfiles.run

ivanova...@gmail.com

unread,
Oct 24, 2020, 2:50:53 PM10/24/20
to AMPL Modeling Language

Thank you very much. The files are changing all the time and also there are many of them (~1000). But the idea of loading the fienames into another file and then reading from it didn't cross my mind.
Reply all
Reply to author
Forward
0 new messages