37

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


24

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


22

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


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


19

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


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

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

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

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


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

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

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

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


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 is a way to search from within mathematica: notebooks = Quiet@FileNames["*.nb", NotebookDirectory[], 2]; Monitor[Select[ Table[{nb, StringJoin@Select[ StringSplit[Import[nb, "Plaintext"], "\n"] , ((If[#, Print["match on:", nb]]; #) &@ StringMatchQ[#, "*NIntegrate*"]) &, 5]}, {nb,notebooks}], #[[2]] !...


12

Build your own Here I create a Dataset of files, taking advantage of the "Rules" option for FileDate. You can add your own information relevant for files or directories in the respective sections after DirectoryQ. Just as a playful example I added FileHash which may slows down things considerably. lstlra[dir_] := Dataset[ <|(* For all files and ...


12

Mathematica allows text searching using regular expressions (based on the PCRE library). It would take some work to re-implement the whole grep functionality within Mathematica, but for your concrete example grep -nr -C 2 <pattern> it is as easy as follows: ClearAll[Grep] Grep[files_List, patt_, c_Integer: 0, style : {__} : {Red, Bold}] := ...


11

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


11

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


11

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


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 :


11

The simplest and most efficient way would probably be using the common wc external utility. For example, In[33]:= Import["!wc ~/test.m", "Table"] Out[33]= {{6, 5, 56, "/Users/szhorvat/test.m"}} You'll get wc by default on Linux/OSX, but you can install it on Windows too.


11

In Mathematica 10.0.0 for Windows, I have experienced similar problems. When non-ASCII characters were placed after \ in a string, they were decoded in a strange way. (Character '\' is used as a path separator in Windows). ToCharacterCode["\\a", "Unicode"](*OK*) {92, 97} ToCharacterCode["\\", "Unicode"](*OK*) {92} ToCharacterCode["μ", "Unicode"](*OK*) {...


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