为什么 Julia 将垃圾数据打印到文件中?

Why Julia is printing junk data to the file?

我是 Julia 的新手,这可能是一个非常愚蠢的问题 :) 我是 运行 Julia 的计算者,想将结果输出到文本文件。主程序包含一个 for 循环。在每个循环之后,应该在输出文件中添加包含该迭代结果的一行(append)。每行包含多个值,它们应该用 space.

分隔

我查看了 Julia 文档,语法似乎与 C++ 非常相似。我已经使用以下代码对其进行了测试。

using Distributions
f = open("hello.txt","w")
write(f,"Hello again.")
close(f)

numbers=rand(5)

f = open("hello.txt","a")
write(f,numbers)
close(f)

f = open("hello.txt","a")
numbers=rand(5)
print(numbers)

write(f,numbers)

close(f)

在这里,我将随机数写入一个文件,前面是一个通用的 hello 语句。但是输出文件看起来像这样,尽管数字数组包含浮点数(在控制台输出中验证)。

Hello again.�7D����?L'Uf���?8��f��?���>��?����XX�?�x�m��?Y�]���?�v�S���?x���]�?�zPL�?

当然,我在做一些傻事。以前从未报告过此问题。 我不知道这里出了什么问题。

作为一种好的做法,我们是否需要在追加每一行之后放置 close(f)/flush(f)(如果通过 for 循环追加数据)或在操作结束时使用 close(f)够了吗?

提前谢谢你。 (朱莉娅 1.6,Linux 64 位)

来自documentation of write

Write the canonical binary representation of a value to the given I/O stream or file.

您似乎需要数字的“文本表示”,那么您应该使用 print。然而,对于 Strings,二进制表示是相同的,所以这就是为什么 write 使用字符串。

julia> open("file.txt", "w") do io
           println(io, "Hello")
           println(io, rand(3))
       end

shell> cat file.txt
Hello
[0.11312836652899494, 0.22752036377169926, 0.04622217336925327]

should we need to put close(f)/flush(f) after appending each line(in case of appending data through for loop ) or using close(f) at the end of operation suffice?

流在 closeflush 编辑。

另一种选择是将 Delimited files modulewritedlm 函数一起使用:

using DelimitedFiles

julia> open("hello.txt", "a") do io
            writedlm(io, numbers)
       end

但据我了解,这似乎是特定于写数字的。