I was wondering if there is some standard "correct" way of creating temp files, then doing some work on then, and then deleting them. In my case, I have some code to generate an SVG file. But then, I want to create a function that writes a PDF file, and I require first generating the SVG, converting it to PDF and saving the PDF. Hence, my code involves creating a temp SVG file. Here is some possible code:
function savesvg(plt::Union{Mark,D{Mark}}; height=400, pad=10)
img = string(drawsvg(plt, height=height, pad=pad))
# Create a temporary file
temp_file_path = tempname()
try
open(temp_file_path, "w") do file
write(file, img)
end
# Use the temporary file as needed
finally
# Delete the temporary file after use
rm(temp_file_path; force=true)
end
end
I was wondering if there is some "don'ts" in here, or if this is how to properly handle it.
There's a mktemp
method that does that stuff for you:
mktemp(f::Function, parent=tempdir())
Apply the function f to the result of mktemp(parent) and remove the temporary file upon completion.
Hmm, I'm trying to figure out how to use this function.
Thanks for the tip, @Sundar R
Your function pretty much becomes
function savesvg(plt::Union{Mark,D{Mark}}; height=400, pad=10)
img = string(drawsvg(plt, height=height, pad=pad))
mktemp() do _, file
write(file, img)
end
end
If you need to work with multiple temporary files, it can be practical to generate a temporary directory instead.
mktempdir() do tmpdir
path1 = joinpath(tmpdir, "file1")
path2 = joinpath(tmpdir, "file2")
...
end
Davi Sales Barreira has marked this topic as resolved.
Last updated: Nov 06 2024 at 04:40 UTC