How to close file after request

Question:

files = {'file': ('output.mp3', open('output.mp3','rb'), 'audio/mpeg')}

I am using this for POST request but after usage trying to delete it with os.remove and it gives "it’s used by a process". How to close file after?

Asked By: wutwut

||

Answers:

You can use with ...:

import os
import requests

# open the file and send it
with open("output.mp3", "rb") as my_file:
    files = {"file": ("output.mp3", my_file, "audio/mpeg")}
    r = requests.post(url, files=files)
    # ...

# file is closed now, remove it
os.remove("output.mp3")
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.