Skip to main content

Export of all notebook files as text files


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;


Answer



How about:


Export[
StringDrop[path, -2] <> "txt",
StringRiffle[
NotebookImport[path, "Input" -> "InputText"],
"\n"
]
]

Comments