不使用 Export 将向量写入文件
我有兴趣将多个向量写入文件,以便每个向量在文件中形成一行,并在生成后立即写入文件。向量的元素需要用单个空格分隔,并且我不想在向量中包含 { }
括号。基本上,我想模仿 C 的 fprintf("file", "%f %f %f\n")
功能。
这就是我所拥有的。有更好的方法吗?
st1 = OpenWrite["C:\\junk\\mu.out", FormatType -> OutputForm];
vt = Table[
v = RandomReal[{0, 1}, 5];
For[j = 1, j <= Length[v], j++,
WriteString[
st1,
SequenceForm[NumberForm[v[[j]], ExponentFunction -> (Null &)],
" "]
]
];
Write[st1, ""];
v,
{200}
];
In[3]:= Close[st1]
Out[3]= "C:\\junk\\mu.out"
基于精彩的 Riffle 函数,由 Arnoud 和 Mr. Wizard 提供,如下,我将其修改如下:
WriteVector[stream_, vector_] :=
Apply[WriteString[stream, ##, "\n"] &,
Riffle[Map[NumberForm[#, ExponentFunction -> (Null &)] &, vector],
" "]
]
I am interested in writing multiple vectors to a file such that each vector forms one row in the file, and is written to the file as soon as it is generated. The elements of the vector need to be separated by a single space, and I do not want to include the { }
parentheses for the vector. Basically, I want to mimic the fprintf("file", "%f %f %f\n")
functionality of C.
Here is what I have. Is there a better way of doing this?
st1 = OpenWrite["C:\\junk\\mu.out", FormatType -> OutputForm];
vt = Table[
v = RandomReal[{0, 1}, 5];
For[j = 1, j <= Length[v], j++,
WriteString[
st1,
SequenceForm[NumberForm[v[[j]], ExponentFunction -> (Null &)],
" "]
]
];
Write[st1, ""];
v,
{200}
];
In[3]:= Close[st1]
Out[3]= "C:\\junk\\mu.out"
Based on the wonderful Riffle function, courtesy Arnoud and Mr. Wizard, below, I modified it as follows:
WriteVector[stream_, vector_] :=
Apply[WriteString[stream, ##, "\n"] &,
Riffle[Map[NumberForm[#, ExponentFunction -> (Null &)] &, vector],
" "]
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许是这个?
然后
:然后
检查:
完成后关闭流:
Maybe this?
and:
then:
and check:
close stream when done: