1
$\begingroup$

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!

$\endgroup$
1
  • $\begingroup$ closely related: 5242 $\endgroup$
    – Kuba
    Feb 9, 2017 at 7:09

2 Answers 2

3
$\begingroup$
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...

$\endgroup$
6
  • $\begingroup$ 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! $\endgroup$
    – Syira
    Feb 9, 2017 at 7:26
  • $\begingroup$ Will fail the second time you run it. $\endgroup$
    – Kuba
    Feb 9, 2017 at 9:43
  • $\begingroup$ Hi @Kuba, could you enlighten me as to why it'd fail? $\endgroup$
    – Syira
    Feb 9, 2017 at 10:06
  • $\begingroup$ @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}]; $\endgroup$
    – Kuba
    Feb 9, 2017 at 10:09
  • $\begingroup$ @Kuba Ah I see it. I've used Clear["Global*"]` at the start, thank you:). $\endgroup$
    – Syira
    Feb 9, 2017 at 10:29
1
$\begingroup$

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}];
$\endgroup$
1
  • $\begingroup$ Yes! Exactly what I needed. Thanks for the help! $\endgroup$
    – Syira
    Feb 9, 2017 at 7:15

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