在Julia上同时写入多个文件

Jos*_*uel 3 printing julia

如何在Julia中同时打印多个文件?有没有更清洁的方式:

for f in [open("file1.txt", "w"), open("file2.txt", "w")]
    write(f, "content")
    close(f)
end
Run Code Online (Sandbox Code Playgroud)

Bog*_*ski 6

根据你的问题,我认为你并不是指并行写入(由于操作可能是IO绑定的事实,这可能不会加快速度).

您的解决方案有一个小问题 - 它不保证fwrite抛出异常时关闭.

以下是三种替代方法,即使出现错误,也要确保文件已关闭:

for fname in ["file1.txt", "file2.txt"]
    open(fname, "w") do f
        write(f, "content")
    end
end

for fname in ["file1.txt", "file2.txt"]
    open(f -> write(f, "content"), fname, "w")
end

foreach(fn -> open(f -> write(f, "content"), fn, "w"),
        ["file1.txt", "file2.txt"])
Run Code Online (Sandbox Code Playgroud)

它们给出相同的结果,因此选择是品味的问题(您可以获得类似实现的更多变体).

所有方法都基于以下open函数方法:

 open(f::Function, args...; kwargs....)

  Apply the function f to the result of open(args...; kwargs...)
  and close the resulting file descriptor upon completion.
Run Code Online (Sandbox Code Playgroud)

如果在某处实际抛出异常(仅保证文件描述符将被关闭),请注意仍将终止处理.为了确保实际尝试每个写入操作,您可以执行以下操作:

for fname in ["file1.txt", "file2.txt"]
    try
        open(fname, "w") do f
            write(f, "content")
        end
    catch ex
        # here decide what should happen on error
        # you might want to investigate the value of ex here
    end
end
Run Code Online (Sandbox Code Playgroud)

有关文档,请参阅https://docs.julialang.org/en/latest/manual/control-flow/#The-try/catch-statement-1try/catch.