Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Permission [WinError 32] The process cannot access the file because it is being used by another process

I use the with statement to open the file then why using os.remove() get me Permission [WinError32]? ‘With statement’ should automatically close the file for me.

import subprocess
import requests
import os
filename = "https://www.youtube.com/watch?v=vzH3-8_Y7oo"
dowmload_v = subprocess.getoutput(f'yt-dlp -f 399 {filename}')
cmd = f'yt-dlp -f 399 {filename} --print filename --encoding utf-8'
file_name = subprocess.run(cmd, capture_output=True, shell=True, text=True, encoding='utf-8').stdout
web_link = "http://file.io/"
with open(file_name.strip('\n'), 'rb') as f:
    requests_link = requests.post(web_link, files={'file':f})
    res = requests_link.json()
    the_link = res['link']
    print(the_link)
    os.remove(file_name.strip('\n'))

Is it make sense using atexit?

import atexit
def remove_file(file_name):
    try:
        os.remove(file_name)
    except IOError as e:
        print(f'Could not romove file {e}')

atexit.register(remove_file, file_name)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The ‘with’ statement closes a file once the ‘with’ block is exited. You’ve put the os.remove() method inside the ‘with’ block. So, when the os.remove() method is executed, the file is still open. You need to put the os.remove() method outside the ‘with’ block for it to work. Modified code:

import subprocess
import requests
import os
filename = "https://www.youtube.com/watch?v=vzH3-8_Y7oo"
dowmload_v = subprocess.getoutput(f'yt-dlp -f 399 {filename}')
cmd = f'yt-dlp -f 399 {filename} --print filename --encoding utf-8'
file_name = subprocess.run(cmd, capture_output=True, shell=True, text=True, encoding='utf-8').stdout
web_link = "http://file.io/"
with open(file_name.strip('\n'), 'rb') as f:
    requests_link = requests.post(web_link, files={'file':f})
    res = requests_link.json()
    the_link = res['link']
    print(the_link)

os.remove(file_name.strip('\n')) #Put this line outside the with block
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading