5

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;
mrz
  • 11,686
  • 2
  • 25
  • 81

1 Answers1

8

How about:

Export[
   StringDrop[path, -2] <> "txt",
   StringRiffle[
      NotebookImport[path, "Input" -> "InputText"], 
      "\n"
   ]
]
Kuba
  • 136,707
  • 13
  • 279
  • 740
  • Wonderful ... that I really need. path corresponds to file in my question. – mrz Apr 27 '16 at 13:38
  • @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. – Kuba Apr 27 '16 at 13:38