Skip to content
Advertisement

How to close file after request

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?

Advertisement

Answer

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")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement