Is write(filename, some_string) discouraged?

In the I/O section of the current Julia manual, the only documented write method is write(io::IO, x), on this webpage:
https://docs.julialang.org/en/v1/base/io-network/#Base.write

If I type ?write the the REPL, I can see a second method write(filename::AbstractString, content). Is this intentionally left out of the manual and discouraged? Should I prefer

open("/path/to/file", "w") do io
    print(io, some_string)
end

over the alternative, write("/path/to/file", some_string)? I’m asking because I’ve always been using the first version, and I wasn’t aware of the second version until I encountered it in an unrelated post.

2 Likes

Well the second version of write pretty much calls the first, so I don’t see a reason not to use it:

julia> @less write("potato.foo", "xyz")
write(filename::AbstractString, a1, args...) = open(io->write(io, a1, args...), convert(String, filename)::String, "w")

And calling print with an io type calls write under the hood:

julia> io = open("potato.foo", "w")
IOStream(<file potato.foo>)

julia> @less print(io, "xyz")
print(io::IO, s::Union{String,SubString{String}}) = (write(io, s); nothing)

So I don’t think there’s a strong reason to prefer one over the others – they exist for convenience/polymorphism.

1 Like

I don’t know about the thinking in the manual but personally I find the ergonomics of the filename method so superior that I always use it when it’s applicable.

1 Like

Ironically it’s used to set up many examples of other functions’ docstrings that are in the docs, you can spot them by searching write(".

1 Like

Just to add that it is common in many packages to provide both a IO argument or a string one that if used refer to a file path to interact with (and open it’s relative stream)…