Stream: helpdesk (published)

Topic: ✔ Creating temporary file, doing work, deleting it


view this post on Zulip Davi Sales Barreira (Feb 23 2024 at 13:17):

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.

view this post on Zulip Sundar R (Feb 23 2024 at 13:22):

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.

view this post on Zulip Davi Sales Barreira (Feb 23 2024 at 13:37):

Hmm, I'm trying to figure out how to use this function.

view this post on Zulip Davi Sales Barreira (Feb 23 2024 at 13:37):

Thanks for the tip, @Sundar R

view this post on Zulip Sundar R (Feb 23 2024 at 13:50):

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

view this post on Zulip Gunnar Farnebäck (Feb 23 2024 at 14:49):

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

view this post on Zulip Notification Bot (Feb 23 2024 at 17:55):

Davi Sales Barreira has marked this topic as resolved.


Last updated: Nov 22 2024 at 04:41 UTC