What is the best way to decompose the contents of a file into a string in Mathematica?

I know this is often asked, but googling does not give a definitive answer for Mathematica, so I thought it would be useful to have this in StackOverflow.

I did this with Import, but it occurred to me that it could be terribly inefficient, Import is such a heavy function.

So the question is, can you improve the following:

slurp[filename_] := Import[filename, "Text"]
+3
source share
1 answer

To import the entire file at the same time, the only other option that I know of is ReadList. It can be persuaded to return the entire file as a single line as follows: 1 :

In[1]:= ReadList["ExampleData/source", Record, RecordSeparators -> {}]
Out[1]:= {"f[x] (: function f :)\r\ng[x] (: function g :)\r\n"}

(:\r \n , .) RecordSeparators. , , , , Import[ <file>, "Text"] . , Read[ <file>, String], , , Read ReadList, .


  • .
+2

Source: https://habr.com/ru/post/1769623/


All Articles