Reputation: 8076
what is the easiest/clearest/simplest/shortest way to A) create a tempfile, B) write a string to it, and C) return the newly created file's name?
This is the best I've got so far:
fname,io = mktemp(); write(io, "<contents>");
# use fname...
Is there some clever, fancy thing I could do with do end
? Anyone have a better suggestion? :) Thanks!
Upvotes: 3
Views: 1987
Reputation: 8566
One way is mktemp() .|> (path->path, io->(write(io, "<contents>"); close(io))) |> first
(this only need 1 semicolon/"line" for safely close the io). I guess do
blocks are mainly for multi-line code:
julia> mktemp() do path,io
write(io, "<contents>")
path
end
"/var/folders/ft/nd_bm3z52152069y78vb71280000gn/T/tmpKLWTBD"
Oops! the do-block way above automatically removes the temporary file upon completion. Shouldn't this just automatically close
the io like open
?!
Upvotes: 5
Reputation: 10984
You can do
f = tempname()
write(f, "Hello")
which, if a "one-liner" is required, you can put on the same line
f = tempname(); write(f, "Hello")
Upvotes: 8