How to import all files of a folder at once?
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).
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:
I've tested this solution in v8 and v9 on Windows platform. Not sure if it will work with other versions and operation systems.
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.