107

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 things....


56

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 ...


34

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 ...


33

There is an undocumented file in the installation directory named specialArgFunctions.tr: NotebookOpen @ FileNameJoin @ { $InstallationDirectory, "SystemFiles", "FrontEnd", "SystemResources" , "FunctionalFrequency", "specialArgFunctions.tr" } This file describes in detail how to attach completion actions to each parameter of listed functions. For ...


29

Maybe something like Select[FileNames["*", "", Infinity], DirectoryQ]


21

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[{" ...


21

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 ...


21

FindFile will tell you which file will be loaded when you ask for a particular package with the backtick syntax. DirectoryName will return the directory that contains a file. Example: In[1]:= FindFile["Combinatorica`"] Out[1]= "/Applications/Mathematica 10.1.app/Contents/AddOns/Packages/Combinatorica/Kernel/init.m" Update: This solution is probably ...


20

Before you start using this, be aware that this is all undocumented and unsupported functionality. It may change at any time, it may crash Mathematica, and it may bite you when you least expect it. I wouldn't be surprised if it turned out that incorrect use messes up the internal state of the front end. Use at your own risk. I tried the examples I show ...


19

With a few rare exceptions, Mathematica is generally unable to work with long path names on Windows. This response presents two strategies to work around this difficulty: extended-length path syntax and short path names (documented in Naming Files, Paths, and Namespaces from the Windows Dev Center). Let's start with a big file name: $big = "...


18

I believe it does work, just not how you expect. :-) From the documentation for PutAppend: Note that there are no quotation marks around filename in the first line. It is not made particularly clear but you can use this syntax with >>>: Range[10] >>> file.txt Which outputs to a file named file.txt directly. This is a special and ...


18

As after half a year there is still no answer, here are some very short answers from my comments: the difference is just the file ending as far as I know. if you have installed MATLAB (or another software which also uses .m file extension) it is easier to let the OS distinguish between MATLAB files and Mathematica packages. because that now seems to be the ...


17

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 ...


17

Since Mathematica is written in the C programming language, it is likely that any file-system status operation is doing nothing more than calling C's built-in functions. In this case, that would be stat. So let's test what stat does on Windows. According to the C language documentation, stat is given the name of something in the file system, and returns a ...


17

FileByteCount will give 0 for empty text files and is very fast (0.00003 seconds per file on my machine). FileByteCount["~/test.txt"]


16

We can do it straightforward in Java using JLink: << JLink` InstallJava[]; replaceBytes[file_, bytes_] := Module[{f, result}, f = JavaNew["java.io.RandomAccessFile", file, "rw"]; writeByte[ff_, {offset_, byte_}] := Module[{old}, ff@seek[offset]; old = ff@readByte[]; ff@seek[offset]; ff@write[byte]; {offset, old} ];...


15

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[]}, ...


15

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 after ...


15

Lots of answers, but none of them leveraging this, so here is another. null[_String] := Null Length @ ReadList["data.txt", null @ String, NullRecords -> True] On my system this is more than three times as fast as Rolf Mertig's CountLines, and a lot more concise as well. If even one Null for every record is too much memory usage then read in blocks of ...


15

If the notebook is saved, you can use: NotebookFileName[EvaluationNotebook[]] or simply (thanks to @rm -rf) NotebookFileName[] and if it's just the file's name you are after: NotebookFileName[] // FileNameSplit // Last Alternatively, even for unsaved notebooks, try: CurrentValue[EvaluationNotebook[], {"NotebookFileName"}]


15

If you want to have the parent directory of the current directory, use ParentDirectory[]. The parent directory of your notebook can be found using: ParentDirectory[NotebookDirectory[]] If you want to set the parent of the notebook directory as the current directory use: SetDirectory[ParentDirectory[NotebookDirectory[]]] Note that if you use ...


15

With[{dirname = FileNameJoin[{NotebookDirectory[], "mydir"}]}, Switch[FileType[dirname], None, CreateDirectory[dirname] (* create dir *), Directory, Null (* do nothing *), File, Print["File with same name already exists!!"] (* error! *) ] ] Ref: FileType, CreateDirectory Ideally, also check if CreateDirectory succeeded.


15

It might be best to use CreateUUID. CreateUUID[] "73ccc27c-687f-4eca-8214-ceeb8a8b7773" The Properties & Relations section shows a way to express this string as an integer if that's what you're after: FromDigits[StringReplace[CreateUUID[], "-" -> ""], 16] 296740835687065620982102887154699649600


14

Your basic requirement is met with: safeExport[file_String, args___] := If[ ! FileExistsQ[file] || ChoiceDialog["File already exists. Overwrite?"], Export[file, args], $Failed ] What you describe as "attributes" (e.g. PlotRange -> All) are known as Options or named optional arguments. (See Attributes for a description of what that term ...


13

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, 5693}...


13

A simple Mathematica-only solution is: CountLines[file_String /; FileExistsQ[file]] := Module[{counter = 0, str = OpenRead@file}, While[ Read[str, Record, NullRecords -> True] =!= EndOfFile, counter++ ]; Close[str]; counter]; which is quite slow of course, so 123 MB (1978142 lines) ...


13

dat = Table[{i, Sin[i], Cos[i], Tan[i]}, {i, 4}] // N; Export["test.txt", dat, "Table", "FieldSeparators" -> " "] FilePrint["test.txt"] 0.8414709848078965 0.5403023058681397 1.5574077246549023 0.9092974268256817 -0.4161468365471424 -2.185039863261519 0.1411200080598672 -0.9899924966004454 -0.1425465430742778 -0.7568024953079282 -0....


13

Edit From version 9 PacletInfo.m file requires "Kernel" extension with Context specification. Without it loading paclets using contexts doesn't work (see old answer). Up to version 8 $Path has precedence over paclet search path no matter how package is loaded. In versions 9.0 - 10.1 paclet search path has precedence over $Path no matter how package is ...


12

Since FileNameJoin was only introduced in Mathematica v7, I thought I'd add a solution using ToFileName for people still running earlier versions (like me): Import[ToFileName[{ NotebookDirectory[], "path", "to", "directory"}, "file.xls"]] So it works in a similar way, but notice that while the path to the file is enclosed in the {...}, the actual file ...


12

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, ...


Only top voted, non community-wiki answers of a minimum length are eligible