Home > Software engineering >  How to close file after request
How to close file after request

Time:10-04

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?

CodePudding user response:

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")
  • Related