2
$\begingroup$

I have a Directory where I store a number of files of the same type (eg .txt). They contain tabled numeric values. I would like to write a routine to import them automatically and store them in a variable that has the same file name. Eg, if there is a file named "uno.txt", then I would like to store the content in a variable named "uno". Manually, I would do uno=Import[dir<>"uno.txt","Table"]

$\endgroup$

2 Answers 2

2
$\begingroup$

First, you need "FileNames" to read the file names with given extension.

Second, you need to extract the file name, using: "FileNameSplit" and "StringDelete" to delete the extension.

Third, you must create a symbol with the name of the file. Because "Set" (=) does not evaluate its first argument, you need "Evaluate".

Here is an example. For your purpose, you must adapt "dir" and the file name.

Clear["Global`*"];
dir = "d:/tmp";
(Evaluate@Symbol[StringDelete[FileNameSplit[#][[-1]], ".txt"]] = Import[#, "Table"]) & /@ FileNames["*.txt", dir]

This will create variables with the name of the files and the content of the files.

$\endgroup$
9
$\begingroup$

You can do it this way, although I would advise against such usage:

Set[Evaluate@ToExpression[FileBaseName[#]], Import[#, "Table"]] & /@
 FileNames[dir <> "*.txt"]

A better way is to import the data, for example, in an association:

Association[FileBaseName[#] -> Import[#, "Table"] & /@ FileNames[dir <> "*.txt"]]
$\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.