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)
>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