1

I'm new to Mathematica. I'm trying to write a script that automatically imports a bunch of .txt files from a directory into different lists.

The files are labeled fileXX.txt where XX are numbers 00 to 10. I'd like to label the lists as listXX. I'm having trouble with 2 things.

1.How to make the loop variable part of the filename and the listname? I tried StringJoin <> but it doesn't work.

2.How to make XX 2-digits always? As in 03 instead of 3, and 04 instead of 4, etc.

Do[list<>XX<>= Import["/directory/file"<>XX<>".txt"],{XX,0,10}];

Thanks in advance!

Syira
  • 13
  • 4

2 Answers2

3
Clear["Global`*"] (*make sure to clear all list* variable first*)
Do[
 fileName = "/directory/file" <> IntegerString[n, 10, 2] <> ".txt";
 Evaluate[Symbol["list" <> IntegerString[n, 10, 2]]] = Import[fileName],
 {n, 0, 50}
 ];

Then

Mathematica graphics

etc...

Nasser
  • 143,286
  • 11
  • 154
  • 359
  • Ah even better! Very useful if I had files with 3-digit or 4-digit names. Auto padding of zeros with IntegerString rids using If statements. Learned something new. Thank you! – Syira Feb 09 '17 at 07:26
  • Will fail the second time you run it. – Kuba Feb 09 '17 at 09:43
  • Hi @Kuba, could you enlighten me as to why it'd fail? – Syira Feb 09 '17 at 10:06
  • @Syira because listxx will have values. So ClearAll["list*"] or something is needed. Try to run this twice: Do[Evaluate[Symbol["list" <> IntegerString[n, 10, 2]]] = ToString@n, {n, 1}]; – Kuba Feb 09 '17 at 10:09
  • @Kuba Ah I see it. I've used Clear["Global*"]` at the start, thank you:). – Syira Feb 09 '17 at 10:29
  • Thanks @Kuba. I actually noticed this when I run it next time. Meant to mention it but forgot. I was restarting the kernel before each time when I was testing this. But using Clear["Global`*"] is good solution also. So I added this now to the answer. – Nasser Feb 11 '17 at 04:13
1

How about something like this:

list = Table[{}, {XX, 1, 10}]
Do[list[[XX]] = 
   Import["/directory/file" <> 
     If[XX < 10, "0" <> ToString[XX], ToString[XX]] <> ".txt"], {XX, 
   1, 2}];
Dunlop
  • 4,023
  • 5
  • 26
  • 41