Hot answers tagged files-and-directories
59
Preamble
I spent some time and designed and implemented a tiny framework to deal with this problem, over the last two days. Here is what I've got. The main ideas will involve implementing a simple key-value store in Mathematica based on a file system, heavy use and automatic generation of UpValues, some OOP - inspired ideas, Compress, and a few other ...
18
I don't like to answer my own question, but to give an idea of what an answer might be here's my first stab at this (in the form of a toolbar), just try running UtilityDock[] and click "Branch" after saving it.
(Note: I think the best answer wouldn't make use of a toolbar)
UtilityDock := (c =
Cell[BoxData[
ToBoxes[Grid[{{Item[
Row[{" ...
17
Your problem is that you've got a slight misunderstanding of the different types of items that ReadList can read. That's OK, it can be a little confusing.
To begin with: String, Number, Expression, etc. are not sub-types of Record. They are all separate types with their own rules for how they are read. The RecordSeparators option is only applied to ...
14
Sure, use FileNames:
FileNames["myfile.doc", {"C:\\"}, Infinity]
This finds any files named myfile.doc on drive C:.
Add other drives as needed to the list: {"C:\\", "D:\\", . . .}
File names can be given as literal strings, StringExpression string patterns, RegularExpression objects, or abbreviated string patterns.
A method to abort the search ...
13
There are several configuration files that you can use to load functionality at startup. They have the form
($BaseDirectory | $UserBaseDirectory)/(Kernel | FrontEnd)/init.m
where
$BaseDirectory
is for every user on the system and
$UserBaseDirectory
is for you along and Kernel or FrontEnd specifies what you are configuring. In fact, a lot of the ...
13
If your notebook is in the top directory, you can use
Import[FileNameJoin[{NotebookDirectory[], "path", "to", "your", "file.xls"}]
where the string is the relative path from that directory.
If your notebook is elsewhere in the directory tree and you want to set paths relative to a different directory, then you could define a global $ParentDirectory and ...
12
If I'm not mistaken the second asterisk in your line
FileNames["*",{"*"},Infinity]
should be replaced with the location of the directory you want to look in.
In case of the directory where your notebook lives in this would be:
FileNames["*", {NotebookDirectory[]}, Infinity]
or, for the current directory, this would be:
FileNames["*", {Directory[]}, ...
11
Maybe, displaying the bytecount of every output expression in tooltips or status area:
$Post = Tooltip[#, ByteCount[#]] &
or
$Post = StatusArea[#, ByteCount[#]] &
To delete all generated cells in the notebook, evaluate
FrontEndExecute[FrontEndToken["DeleteGeneratedCells"]]
or
FrontEndTokenExecute["DeleteGeneratedCells"]
To delete all ...
11
Here are some commands I ran on my machine to generate a few files, and give them some history:
touch foo1 foo2 foo3 foo4
touch foo3
cat foo2
Here are the files:
files = FileNames["foo*"]
(*
==> {"foo1", "foo2", "foo3", "foo4"}
*)
The most recently changed file:
SortBy[files, FileDate] // Last
(*
==> "foo3"
*)
The newest file:
SortBy[files, ...
11
From the help
OpenWrite["file"] open an output stream to a file, wiping out the previous contents of the file
... it's gone, you deleted it :
8
I recommend an external command approach. On Windows this looks like this:
command = "!dir \"" <> Directory[] <> "\" /A:D /S /B";
ReadList[command, String]
This can be many times faster than the Select - FileNames method.
Select[
FileNames["*", "C:\\Data & Images", Infinity],
DirectoryQ
] // Length // AbsoluteTiming
{6.7413856, ...
8
SystemDialogInput["FileSave"] will do this for you.
Something like
fileName = SystemDialogInput["FileSave"]
If[fileName != $Canceled, Export[fileName, myData]]
should do the whole trick. The fire extension determines the type of export (if MMA knows it and supports it).
Preselecting a directory path and filtering allowable file extensions can be done as ...
8
With $UserBaseDirectory/Kernel/init.m the most obvious place to put code which should be autoloaded has been mentioned.
But I think it might be worth mentioning that there is also the Autoload directory within $UserBaseDirectory where you can put any package file or package directory and those will automatically be loaded at startup. For the purpose ...
8
As a software developer, I'd suggest a non-mathematica solution to the general problem of versioning. Use a version control system, such as git, that supports text files (i.e. notebooks).
If you both (1) use an external version control system, where you explicitly commit after any "interesting" change, and (2) setting the default configuration to ...
8
If you use Import/Export to load/save .mx files, instead of DumpSave, then the variable does not get embedded in the file, and you can assign it to any variable of choice in the new session.
x = RandomReal[1, {100, 100}];
Export["~/tmp.mx", x];
y = Import["~/tmp.mx"];
x == y
(* True *)
7
Functionality you are looking for is included in Wolfram Player Pro. Detailed functionality difference relative to Free Wolfram CDF Player and Mathematica is listed here:
CDF Player, Player Pro, and Mathematica Features Comparison Chart
If including your data in CDF is possible in your case then
1) This blog (2nd example) shows simplest case of ...
7
On Linux, you can combine your favorite version control system (Git in this example) with inotify to automatically commit your changes to the repository whenever your .nb file is saved.
Create a Git repository, and save your notebook (say notebook.nb) in the repository. Use inotifywait to automatically run git commit notebook.nb --allow-empty-message -m '' ...
7
Amending the file directly would indeed require something like .Net.
If you were willing to consider an import-export roundtrip but with a spreadsheet like interface in Mathematica, then something like this might work:
rawdata = (Import["myspreadsheet.xlsx"][[2]]);
(* where 2 is the number of the worksheet you want to use *)
newdata = TableView[rawdata]
...
7
As I mentioned in a comment, using string patterns makes for lot cleaner code. Here's a simple way to do it using StringCases:
changeFileName = StringCases[#, NumberString ~~ "." ~~ f__ :> f] &;
changeFileName@"1234.name.pdf"
(* {"name.pdf"} *)
If you have a list of file names, map the above onto the list.
You can progressively build upon this for ...
6
First create your points, running from 0 to 2 Pi at intervals of 0.01.
points = Table[{x,Sin[x]}, {x, Range[0, 2 \[Pi], .01]}];
You can plot them with:
ListLinePlot[points]
And export them to a csv file with:
Export["points.csv", points]
6
You can select the points from the plot and write it to file with Export:
pl = Plot[Sin[x], {x, 0, 2 Pi}];
The Points are arguments to a Line directive in the Plot function:
Position[pl, Line]
output is: {{1, 1, 3, 2, 0}} the zero is the Head of the Line directive, the points are the argument:
points = pl[[1, 1, 3, 2, 1]];
Alternatively you can ...
6
If you look at this
#!/usr/local/bin/math8.0.4/MathematicaScript -script
$HistoryLength=0;
$pwf=FileNameJoin[{NotebookDirectory[],FileBaseName[NotebookFileName[]]}];
$pwf = "test";
$parameterfile=StringJoin[$pwf,".dat"];
Print[$pwf];
Print[$parameterfile];
Print[$InputFileName];
you will see that the Print statements work just fine - What requires the ...
6
If I use the option Method->"Queued" within Button, this works
Button["Export",
Export[SystemDialogInput["FileSave"], Plot[Cos[x], {x, 0, Pi}],
"PDF"], Method -> "Queued"]
Otherwise, "Preemptive" will be the default, making it possible that not enough time is allocated for the Button action to complete. See the reference docs on ...
6
The following is a slight modification to @amr's code.
It shows a directory tree using TreeForm[], with a button at each vertex. When the button is pressed, it opens a dialog with the list of the files contained in that directory.
ellipsizeMax = 8;
ellipsize[str_] :=
If[StringLength[str] > ellipsizeMax,
StringTake[str, ellipsizeMax] <> ...
5
Try this:
SystemDialogInput["FileOpen", {"Data", {"Data" -> {"*.data", "*.dat"}}}]
The doc page for SystemDialogInput describes under "More Information" how to create new file types by listing the patterns they match.
5
Manipulate does not directly support a control type called "FileNameSetter", but fortunately it is possible to use custom controls (both in Manipulate and other functions), as described e.g. in the Control documentation:
{u,func} an arbitrary control from a function
The trick to getting it working is that func must ...
5
Here's how I'd do it. Hopefully it's general enough, and easy to understand.
Start by defining a base directory:
base = "c:\\mse\\test\\";
I usually use Import to get a list of filenames. If you give it a directory name, it will return a list of all the files under that directory (including subdirectories):
original = Import[base]
...
5
The best way to do this would be using scheduled tasks. This way, you have greater flexibility over starting/stopping and quitting the task than with Dynamic. Here's an example:
Begin["Kale`"];
fileName = "~/foo.txt";
lastModified = {};
updatedQ := With[{modificationDate = FileDate[fileName, "Modification"]},
If[lastModified == ...
5
Here's a relatively straightforward "first version":
ellipsizeMax = 8;
ellipsize[str_] := If[StringLength[str] > ellipsizeMax, StringTake[str, ellipsizeMax] <> "\[Ellipsis]", str];
readDir[currentDirectory_, 0] := ellipsize[FileNameTake[currentDirectory]];
readDir[currentDirectory_, level_] := Module[{joinedFiles, perFile},
...
5
A quick look at the documentation for Export reveals that Mathematica supports a range of Export formats and that there is a guide on how to import and export data in different formats.
In that guide it states:
Export["file", list, "Table"] writes out data separated by spaces, with numbers given in C or Fortran-like form, as in 2.3E5 and so on.
This ...
Only top voted, non community-wiki answers of a minimum length are eligible



