I have a list of files all indexed as filename1,filename2,filename3,... up to 50, all in the same directory, and I wanted an AppendTo them to a list and ToExpression in index order 1,2,...,50.

Does anyone know of a good method to do this? Thanks!

  • $\begingroup$ You can obtain a list of filenames, e.g., by list = FileNames[FileNameJoin[dir, "filename*"]] where dir is a string specifying the directory. Afterwards you can Map anything over that list, for example, Import... $\endgroup$ – Henrik Schumacher Feb 4 '19 at 18:08
  • $\begingroup$ Thanks. will it do so indexed numerically? the order it is stored is crucial $\endgroup$ – MKF Feb 4 '19 at 18:11
  • $\begingroup$ Or will it do something like store filename10,11,12,...,19,1,20,21,...,29,2? This is the index order if you consider FileNames and I fear therefore it will not order my index correctly $\endgroup$ – MKF Feb 4 '19 at 18:12
  • $\begingroup$ The order is the typical lexicographical order of strings. So, yes, that may happen. That's why one should enumerate file names with leading zeroes. $\endgroup$ – Henrik Schumacher Feb 4 '19 at 18:12
  • $\begingroup$ Thanks @Henrik How could this be avoided therefore? $\endgroup$ – MKF Feb 4 '19 at 18:14

You may generate the list of files with

Table[FileNameJoin[{dir,"filename" <> IntegerString[i]}], {i, 1, 50}]

where dir is a string containing the path to said directory.

  • $\begingroup$ So I tried Do[AppendTo[ ToExpression[Import["filename" <> IntegerString[i], "List"]], completelist], {i, 1, 50}] but to no avail $\endgroup$ – MKF Feb 4 '19 at 18:33
  • $\begingroup$ You have reverse the syntax of AppendTo Try completelist = {}; Do[ AppendTo[completelist, ToExpression[Import["filename" <> IntegerString[i], "List"]]], {i, 1, 50}] or something similar... $\endgroup$ – Henrik Schumacher Feb 4 '19 at 18:40
  • $\begingroup$ Oh my goodness of course, thanks $\endgroup$ – MKF Feb 4 '19 at 18:41
  • $\begingroup$ You're welcome. $\endgroup$ – Henrik Schumacher Feb 4 '19 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.