46
$\begingroup$

I know how to import one textfile by calling its name

filestring = Import["myfile.tex", "Text"];

Then "filestring" is a string with the myfile content.

How do I import all N text files in one folder? So that I get, for example, a list with N strings.


Bonus: Can I maybe also not only import all at once but specify "get the last three text files" or "get the first ten" out of that folder into my list?

$\endgroup$

6 Answers 6

70
$\begingroup$

Have a look at FileNames:

files=FileNames["*.pdf", NotebookDirectory[]]

{"a.pdf","b.pdf","c.pdf"}

will get you a list of all files in the directory where your notebook resides (of course you can choose any path) that match "*.pdf". You can then import the files like this:

Import[#]&/@files

or if you want certain files (look at the help for Part and Span):

Import[#]&/@files[[-3;;-1]] (*last three files*)
Import[#]&/@files[[1;;10]]  (*first ten files*)

If you want to use more arguments with Import like in your question then you can add them after the #, e.g. like this: Import[#,"Text"]&/@files. Otherwise you can save typing effort by choosing the the shorter version Import/@files (as pointed out by @AlbertRetey).

$\endgroup$
6
  • $\begingroup$ Ya, I figured the rest before the edit myself, thanks. I now ended up with: FileNames["*.tex", "MY PATH"]; Part[%, 1 ;; 3]; Import[#, "Text"] & /@ % $\endgroup$
    – Nikolaj-K
    Commented May 6, 2012 at 15:39
  • 1
    $\begingroup$ Consider also using Select, as you can weed out directories via Select[ FileNames[...], !DirectoryQ[#]&], or if they wish to exclude hidden files (i.e. starting with a "." on a unix/linux based system - mac included), the predicate can be expanded to !(DirectoryQ[#] || StringMatchQ[#, "." ~~ ___])&. $\endgroup$
    – rcollyer
    Commented May 6, 2012 at 15:41
  • 5
    $\begingroup$ @NickKidman sidenote: using % (aka Out) can result in confusion if you don´t take care of the evaluation order (e.g. if you do not put all depending code into one cell). $\endgroup$
    – Yves Klett
    Commented May 6, 2012 at 15:44
  • $\begingroup$ @YvesKlett: is there a certain reason to use Import[#]&/@files instead of the simpler Import/@files? $\endgroup$ Commented May 7, 2012 at 19:59
  • $\begingroup$ @AlbertRetey I just wanted to show the way if the OP wanted to use Import with additional arguments or options. $\endgroup$
    – Yves Klett
    Commented May 7, 2012 at 20:03
5
$\begingroup$

Well, I dug out this question because I accidentally found another way for getting the paths of files today and I can't help posting it as an answer somewhere XD.

It should be mentioned that, this help page has already told us some ways to insert paths without any Mathematica code while it doesn't tell us that there's a even simple way to get the paths of the files, that is:

Ctrl+C and Ctrl+V.

Now the whole process will be quite simple, first input this incomplete code in the notebook:

Import /@ {}

Then find the files you suppose to import and select them with Ctrl+A, Ctrl+click, Shift+click, etc. Press Ctrl+C and move to the code above, place the cursor between the {} and Ctrl+V, run the code and you'll get the expected result.

I think this solution is as fast as, or even faster than the solutions with Mathematica codes especially when we only want to input a single file or the name of the target files are not so regular.

Here's a screencast:

enter image description here

I've tested this solution in v8 and v9 on Windows platform. Not sure if it will work with other versions and operation systems.

$\endgroup$
6
  • 1
    $\begingroup$ Doesn't work on a mac. Also, when you paste it, it inserts it as a symbol, not a string and doesn't place a comma between multiple strings. So you'll have to manually insert the quotes and commas to use this... waay too much work. $\endgroup$
    – rm -rf
    Commented Nov 16, 2012 at 14:49
  • 1
    $\begingroup$ This also doesn't work right on Windows 7 with v7, as the strings are inserted without properly escaped backslashes and without commas separating, BUT it works if using Szabolcs's Paste Tabular Data palette. (Table button.) $\endgroup$
    – Mr.Wizard
    Commented Nov 16, 2012 at 14:58
  • $\begingroup$ @rm-rf I supplied the version information of my Mathematica and a snapshot: those commas and backslashes and quotes are not added by me. $\endgroup$
    – xzczd
    Commented Nov 17, 2012 at 9:33
  • $\begingroup$ @xzczd Works as described on 10.0.2 on Win 7. Doesn't work with 10.0.2 on OS X Mavericks. $\endgroup$ Commented Jan 13, 2015 at 17:36
  • $\begingroup$ What about using something like Import[SystemDialogInput["FileOpen"]] (or the version with Map[] if you expect to import multiple files)? $\endgroup$ Commented Jan 8, 2017 at 10:11
3
$\begingroup$

I actually always use the FileNames approach as Yves suggested which gives you better control about which files to import. For completenes I just wanted to add that Import itself knows about directories. The following will show all files from a directory (warning: this traverses all subdirectories recursively!):

 Import[dirname]

and this will import the contents of all text files in a given directory (and all subdirectories):

 Import[dirname,"*.txt"]

see the documentation in "ref/format/Directory" for more details.

$\endgroup$
1
$\begingroup$

The way how I do it is to firstly generate the name of the input files into a table of strings, here's an example

nameInput = Table[StringTemplate["/Users/Projekt/output/input/b5_t`t`_a`a`.dat", InsertionFunction -> (ToString@NumberForm[#, {2, 2}] &)]@<|
 "t" -> 0.01 k, "a" -> 0.01 l|>, {k, 1, 3}, {l, 0, 4}];

which produces the following

  {{"/Users/Projekt/output/input/b5_t0.01_a0.00.dat", 
  "/Users/Projekt/output/input/b5_t0.01_a0.01.dat", 
  "/Users/Projekt/output/input/b5_t0.01_a0.02.dat", 
  "/Users/Projekt/output/input/b5_t0.01_a0.03.dat", 
  "/Users/Projekt/output/input/b5_t0.01_a0.04.dat"}, 
  {"/Users/Projekt/output/input/b5_t0.02_a0.00.dat", 
  "/Users/Projekt/output/input/b5_t0.02_a0.01.dat", 
  "/Users/Projekt/output/input/b5_t0.02_a0.02.dat", 
  "/Users/Projekt/output/input/b5_t0.02_a0.03.dat", 
  "/Users/Projekt/output/input/b5_t0.02_a0.04.dat"}, 
  {"/Users/Projekt/output/input/b5_t0.03_a0.00.dat", 
  "/Users/Projekt/output/input/b5_t0.03_a0.01.dat", 
  "/Users/Projekt/output/input/b5_t0.03_a0.02.dat", 
  "/Users/Projekt/output/input/b5_t0.03_a0.03.dat", 
  "/Users/Projekt/output/input/b5_t0.03_a0.04.dat"}}

This works well especially when your input files follows a pattern. Then you can simply import your data by importing the table

data = Table[Import[nameInput[[i, j]]], {i, 1, 3}, {j, 1, 4}];

hope this helps!

$\endgroup$
1
$\begingroup$

Make a super simple program:

importdat := (# // Import[#, "Table"] &) &

and then use:

FileNames["*"] // importdat /@ # & // (nameofdataset = #) &;

you can narrow down the dataset to one with specific string by playing with *

$\endgroup$
2
  • $\begingroup$ Might be better to use FileNames["*.txt"] or whatever other file type you are trying to import. $\endgroup$
    – bbgodfrey
    Commented Jan 8, 2017 at 16:55
  • 1
    $\begingroup$ This is not super simple at all. Your importdat definition in unnecessarily complicated. You can replace it with importdat := Import[#, "Table"] & and it will do the same thing. $\endgroup$ Commented Feb 9, 2017 at 13:38
0
$\begingroup$

For some basic data files, imported in such a way that each can be plotted, consider this sort of delimited file:

{0, 0}
{1/4, 0.05262298820443631}
{1/2, 0.0708342218540585}
{3/4, 0.0828484992154531}

Then, use, with the file stored in fold1 (in the right directory on your computer, here this is home/Downloads/data/),

files = FileNames["*.txt", "/home/Downloads/data/fold1"]
datlist = ToExpression[Import[files[[#]], "List"]] & /@ Range[Length@files]

to get at all the files, then e.g.

ListPlot[datlist[[1]], Joined -> True]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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