Home > Net >  how do i close multiple files after uploading them via a single POST request?
how do i close multiple files after uploading them via a single POST request?

Time:01-01

files =  [('file', open(os.path.join(MONITOR_DIRECTORY, f), 'rb')) for f in new_files] # wrap all new files in list for POST request 
response = requests.post(SERVER_IP, files = files)

after i wrap my files and send/upload it to a flask server via a POST request, i need to be able to delete the files locally. however when i try to remove the files via os.remove(), i get a permission error (WinError32).

I know that there is a with open() command which I can use for opening and closing individual files, but in this case because I want to send multiple files in a single request, how can I remove them at once after the request is sent?

CodePudding user response:

Not sure why would you need to 'open' the files. but if your're post methoid doesn't requrie batch of files you can do it individually with for loop and file context:

for f in files:
   with open(os.path.join(MONITOR_DIRECTORY, f), 'rb'):
      # I don't know why you're using this tuple but I just added it again for you
      response = requests.post(SERVER_IP, files = [('file', f)]) 

CodePudding user response:

You have references to the file objects in files. Just close them.

# your code:
files =  [('file', open(os.path.join(MONITOR_DIRECTORY, f), 'rb')) for f in new_files] # wrap all new files in list for POST request 
response = requests.post(SERVER_IP, files = files)

# then afterwards:

for (_, f) in files:
    f.close()
  • Related