4
$\begingroup$

I want to export all my notebook files located in a root directory as text files.

Below is a simple code that I use.

Ho can I export "only" the necessary text content of each notebook file?

ChoiceDialog[{FileNameSetter[Dynamic[imageDir], "Directory"], 
   Dynamic[imageDir]}];
notebookFiles = FileNames["*.nb", imageDir, Infinity]
num = Length[notebookFiles];

Table[
  file = notebookFiles[[i]];
  notebookText = Import[file, "Text"];
  Export[StringJoin[StringTake[file, StringLength[file] - 2], "txt"], 
   notebookText]
  , {i, 1, num}
  ];

E.g.:

If I have a notebook file with the following content:

a = 10;

then the corresponding text files contains:

(* Content-type: application/vnd.wolfram.mathematica *)

(*** Wolfram Notebook File ***)
(* http://www.wolfram.com/nb *)

(* CreatedBy='Mathematica 10.4' *)

(*CacheID: 234*)
(* Internal cache information:
NotebookFileLineBreakTest
NotebookFileLineBreakTest
NotebookDataPosition[       158,          7]
NotebookDataLength[       941,         38]
NotebookOptionsPosition[       698,         25]
NotebookOutlinePosition[      1046,         40]
CellTagsIndexPosition[      1003,         37]
WindowFrame->Normal*)

(* Beginning of Notebook Content *)
Notebook[{
Cell[BoxData[
 RowBox[{
  RowBox[{"a", "=", "10"}], ";"}]], "Input",
 CellChangeTimes->{{3.670749642550244*^9, 3.6707496447180743`*^9}}]
},
WindowSize->{1092, 1175},
WindowMargins->{{Automatic, 238}, {Automatic, 0}},
FrontEndVersion->"10.4 for Microsoft Windows (64-bit) (February 25, 2016)",
StyleDefinitions->"Default.nb"
]
(* End of Notebook Content *)

(* Internal cache information *)
(*CellTagsOutline
CellTagsIndex->{}
*)
(*CellTagsIndex
CellTagsIndex->{}
*)
(*NotebookFileOutline
Notebook[{
Cell[558, 20, 136, 3, 31, "Input"]
}
]
*)

(* End of internal cache information *)

Instead I only would like to create a text file with:

a=10;
$\endgroup$
  • $\begingroup$ What version are you working with? $\endgroup$ – Kuba Apr 27 '16 at 12:42
  • $\begingroup$ 10.4.0, see my updated question ... $\endgroup$ – mrz Apr 27 '16 at 12:43
8
$\begingroup$

How about:

Export[
   StringDrop[path, -2] <> "txt",
   StringRiffle[
      NotebookImport[path, "Input" -> "InputText"], 
      "\n"
   ]
]
$\endgroup$
  • $\begingroup$ Wonderful ... that I really need. path corresponds to file in my question. $\endgroup$ – mrz Apr 27 '16 at 13:38
  • $\begingroup$ @mrz yes, sorry for not being consistent ;) I'm glad you find it useful, NotebookImport isn't the fastest function but I don't think I know how to do that faster without coding to much. $\endgroup$ – Kuba Apr 27 '16 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.