开发者

What's the best way to slurp the contents of a file into a string in Mathematica?

I know this is asked commonly but googling doesn't turn up a definitive answer for Mathematica so I thought it would be valuable to have this on StackOverflow.

I've been doing this with Import but it occurred to me that that might be horribly inefficient, Import being such a heavyweight function开发者_开发问答.

So the question is, can you improve on the following:

slurp[filename_] := Import[filename, "Text"]


For importing the entire file at once, the only other option that I am aware of is ReadList. It can be coaxed to returning the entire file as a single string as follows1:

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

(Note: \r and \n are actually interpreted in the output, but I left them in for readability.) The key is to remove any RecordSeparators. But, I honestly don't think this saves you anything, and Import[ <file>, "Text"] is easier to write. Truthfully, I use Read[ <file>, String] when I have data in a format that isn't covered by the type specifiers used in Read and ReadList, and build a custom function around this operation to load in all of the data.


  1. You can find this in the Reading Textual Data tutorial.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜