PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
Your process is the one that has the file open (via im
still existing). You need to close it first before deleting it.
I don't know if PIL supports with
contexts, but if it did:
import os
from PIL import Image
while True:
img_dir = r"C:\Users\Harold\Google Drive\wallpapers"
for filename in os.listdir(img_dir):
filepath = os.path.join(img_dir, filename)
with Image.open(filepath) as im:
x, y = im.size
totalsize = x*y
if totalsize < 2073600:
os.remove(filepath)
This will make sure to delete im
(and close the file) before you get to os.remove
.
If it doesn't you might want to check out Pillow, since PIL development is pretty much dead.
Exception has occurred: PermissionError [WinError 32] The process cannot access the file because it is being used by another process:
From the comments it is clear that you're either not sharing the code causing the actual problem, or making more changes than was suggested in the comments.
Take this:
from shutil import copy
from os import remove
import moviepy.video.io.VideoFileClip as VideoFileClip
copy('test.mp4', 'new_test.mp4')
stock_footage = VideoFileClip.VideoFileClip(r'new_test.mp4', target_resolution=(1080, 1920))
try:
remove('new_test.mp4')
except PermissionError:
print('as expected')
stock_footage .close()
try:
remove('new_test.mp4')
print('success')
except PermissionError:
print('you will not see this')
Output (assuming you have a test.mp4
in the same location as the script):
as expected
success
Which shows that VideoFileClip
locks the file it opens and calling .close()
on it resolves the issue.
Python WinError 32 The process cannot access the file because it is being used by another process
Your script starts by doing
os.chdir(pdfPath)
so the process running your script is the one holding the pdfPath
directory, and preventing it from being removed by shutil.move
. Just do a chdir
somewhere else before moving it, for example:
chdir("C:/Users/xxx/Desktop/pdf2jpg/")
if os.path.exists(jpgPath):
...
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: after installing python-certifi-win32
I ran into the same issue today. I corrected it by removing two *.pth files that were created when I had installed python-certifi-win32. This prevents python-certifi-win32 from loading when python is run.
The files are listed below, and were located here:
C:\Users\<username>\AppData\Local\Programs\Python\Python310\Lib\site-packages
Files:
python-certifi-win32-init.pth
distutils-precedence.pth
Removing these files allowed me to install/uninstall other modules.
How to tackle this python error - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:
NamedTemporyFile
returns an open file object but you try to open it a second time with open(tempfile.name,"w") as temp_file
. You had a bug in your for loop (closing the files per row written). So,
import csv
import shutil
from tempfile import NamedTemporaryFile
import os
class csvtest():
def editcsv1(self,filename):
filename="data.csv"
with NamedTemporaryFile(dir=r"C:\Users\Sahil\Desktop\python",
mode="w", delete=False) as tempfile:
with open(filename,"r") as csvfile2:
reader=csv.reader(csvfile2)
writer=csv.writer(tempfile)
writer.writerows(reader)
shutil.move(temp_file.name,filename)
os.remove(f.name)
abc=csvtest()
abc.editcsv1(filename)
Getting Python error --PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
It's quite possible that pd.read_csv
isn't properly closing the file since it is crashing mid read, I would try opening the file yourself so that in the except your own program is definitely closing the file and this may fix your issue.
import traceback
import pandas as pd
try:
with open('CBD_BU_FULL.csv', "r") as f:
df = pd.read_csv(f, encoding='UTF-8', dtype=str)
df = df.assign(FILE_TYPE ='BU')
data = df.to_json(orient = "records", lines=False).split('\n')
print(data)
except:
traceback.print_exc(1)
os.rename('CBD_BU_FULL.csv', '/Errored/CBD_BU_FULL.csv')
Related Topics
Weighted Choice Short and Simple
Python: Why Does My List Change When I'm Not Actually Changing It
Django JSONfield Inside Arrayfield
Selenium Unable to Locate Element Only When Using Headless Chrome (Python)
Find Usa Phone Numbers in Python Script
How to Change UI in Same Window Using Pyqt5
How to Change the Datetime Tick Label Frequency for Matplotlib Plots
Recursive Function Returning None
How to Redirect Stderr in Python
Best Way to Determine If a Sequence Is in Another Sequence
Where to Put Django Startup Code
Python Pack() and Grid() Methods Together
Tab Completion in Python's Raw_Input()
How to Get Dict from SQLite Query
How to Find Tags with Only Certain Attributes - Beautifulsoup
Go to a Specific Line in Python
Rename Nested Field in Spark Dataframe
How to Do N-D Distance and Nearest Neighbor Calculations on Numpy Arrays