# Importing multiple files using a for-loop

once again I am stuck solving a seemingly easy problem :(

I would like to make a List of tables by importing data from several txt-Files. Importing the data into a table works so far and I am able to do ListPlots etc.

The txt-file-names follow a simple pattern: txtFile_1.txt, txtFile_2.txt, ...

My take on the problem is the following:

    testList = List[1, 2, 3, 4]
For[i = 1, i < 4, i++
testList[[i]] =
Import["C:\\txtFiles\\txtFile_" <> ToString[i] <> ".txt" <>
ToString[i] <> ".txt", "Data"];
]


Background: I would like to have the tables in the list to be able to access them via testList[[i]] and in order to do consecutive ListPlots via a for-loop etc...

-
Importing with Table will build the desired testList. –  BoLe Mar 30 '13 at 13:22

The short answer is "don't use a For loop".

The longer answer is: you can do this using Table and you definitely don't need to pre-populate testlist. Instead do something like this:

testlist =
Table[Import["C://txtfile_" <> ToString[i] <> ".txt", "Data"], {i, 4}]


You can then access the imported files as testlist[[1]] and so on.

Asides from being shorter code, this approach is more efficient. You could use the file system interrogation functions to work out how many files there are with the right file name pattern, and use that to define the Table iterator.

-
thank you - this is pretty much straight forward and exactly what I have been looking for. –  Probabilitnator Mar 30 '13 at 13:41
testList = Table[Import["C:\\txtFiles\\txtFile_" <>
ToString[i] <> ".txt", "Data"], {i, 4}]


Or, you can map over the files you want to import. Say you have them in the directory where your notebook is saved.

files = FileNames[NotebookDirectory[] <> "*.txt"];
testList = Import[#, "Data"] & /@ files


Both times you will get the list that you want and access.

-
wow - this is easier than I would have thought. I wonder how you gus find out how to do things like that. The mathematica-help isn't that explicit here !! –  Probabilitnator Mar 30 '13 at 13:40
Also, note that Table iterator doesn't need to be an increasing integer, but it can go over a list of files. Table[Import[file, "Data"], {file, files}]. –  BoLe Mar 30 '13 at 13:41
@Probabilitnator Don't agree, I think help is very helpful in Mathematica. But one has to spend some time on it. ;) –  BoLe Mar 30 '13 at 13:44
@Probabilitnator, here's a good place to start: mathematica.stackexchange.com/questions/18/… –  RunnyKine Mar 30 '13 at 16:48
@RunnyKine thank you :) –  Probabilitnator Apr 1 '13 at 9:27

The files don't need to be named nicely, either. Say you have a list of filenames:

allNames = {"filename.txt", "thatFile.txt", "thisfile.txt", ... };


Now you can read them all in:

allData = Table[Import[allNames[[i]],"Data"],{i, 1, Length[allNames]}];


It is not even necessary to use an integer iterator, as in:

allData = Table[Import[name, "Data"], {name, allNames}];

-