PermissionError: [WinError 32] The process cannot access the file - python

I got always the message: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
Yes, i read [enter link description here][1] but it didn't help me.
# pdf_merger2.py
import glob,os,shutil
os.getcwd()
from PyPDF2 import PdfFileMerger
os.chdir(r"auf_comp")
def merger(output_path, input_paths):
pdf_merger = PdfFileMerger()
file_handles = []
for path in input_paths:
pdf_merger.append(path)
with open(output_path, 'wb') as fileobj:
pdf_merger.write(fileobj)
if __name__ == '__main__':
paths = glob.glob('*.pdf')
paths.sort()
merger('data.pdf', paths)
shutil.move(r"data.pdf", r"../data.pdf")
edit:
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\shutil.py", line 788, in move
os.rename(src, real_dst)
PermissionError: [WinError 32] PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'data.pdf' -> '../data.pdf'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\typ42\Downloads\latextest\merge.py", line 22, in <module>
shutil.move(r"data.pdf", r"../data.pdf")
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\shutil.py", line 803, in move
os.unlink(src)
PermissionError: [WinError 32] PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'data.pdf'
[1]: https://stackoverflow.com/questions/27215462/permissionerror-winerror-32-the-process-cannot-access-the-file-because-it-is

Related

shutil.move PermissionError: [WinError 5] Access is denied

Hi i tried to move some local files to a nas but it raises an Access is denied error. I have compiled the script to .exe file with auto-py-to-exe. I tried to set some rights to the local folder but it didn't work. Run the script with adminrights but now i haven't rights on the nas, the rights on the nas i can't change.
python script:
import os, shutil, time, logging, stat
logging.basicConfig(filename="test.log", format='%(asctime)s %(message)s\n', encoding='utf-8')
try:
start = int(input("Startdate: "))
end = int(input("Enddate: "))
filePath = "D:/path/to/file"
storePath = "Z:"
count= 0
for file in os.listdir(filePath):
fname = int(file.split("_")[0])
if fname >= start and fname <= end:
count += 1
print(f"You are about to move {count} folder from {filePath} to {storePath}!")
answer = input("Do you want to move these files?(y/n): ")
if answer != "y":
print("Cancelled!")
exit()
for file in os.listdir(filePath):
fname = int(file.split("_")[0])
if fname >= start and fname <= end:
try:
os.chmod(f"{filePath}/{file}", stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
except:
logging.log(f"\nRights were not changed for\n{filePath}/{file}\n\n")
shutil.move(f"{filePath}/{file}", f"{storePath}/{file}")
print(f"{filePath}/{file} moved to {storePath}/{file}")
time.sleep(60)
except Exception as e:
logging.exception(e, exc_info=True)
logfile:
2022-11-15 16:03:25,839 [WinError 5] Access is denied: 'D:/path/to/file/20211124_1_6377401797037988\\20211124.txt'
Traceback (most recent call last):
File "shutil.py", line 824, in move
OSError: [WinError 17] The system cannot move the file to a different disk drive: 'D:/path/to/file/20211124_1_6377401797037988' -> 'Z:/20211124_1_6377401797037988'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 39, in <module>
File "shutil.py", line 842, in move
File "shutil.py", line 758, in rmtree
File "shutil.py", line 621, in _rmtree_unsafe
File "shutil.py", line 619, in _rmtree_unsafe
PermissionError: [WinError 5] Access is denied: 'D:/path/to/file/20211124_1_6377401797037988\\20211124.txt'
Your path to file flips the '/' to '\' at the filename. You can use 'r' in front of file names to ensure the slashes are maintained
https://docs.python.org/3/reference/lexical_analysis.html#:~:text=Both%20string%20and,is%20not%20supported.

PermissionError: [Errno 13] Permission denied: Python

I have a script that is called from DJango, but it doesn't execute instead it gives PermissionError: [Errno 13] Permission denied. I'm using CMD on Windows as admin.
Here is how I'm calling:
cmd = os.path.join(os.getcwd(), "D:/commerceTest/cs50-commerceM/Photo/GFPGAN/inference_gfpgan.py --upscale 2 --model_path D:/commerceTest/cs50-commerceM/Photo/GFPGAN/experiments/pretrained_models/ --test_path inputs/whole_imgs/GFPGANCleanv1-NoCE-C2.pth --save_root D:/commerceTest/cs50-commerceM/Photo/GFPGAN/results")
#os.system("python D:/commerceTest/cs50-commerceM/Photo/GFPGAN/inference_gfpgan.py --upscale 2 --model_path D:/commerceTest/cs50-commerceM/Photo/GFPGAN/experiments/pretrained_models/ --test_path inputs/whole_imgs/GFPGANCleanv1-NoCE-C2.pth --save_root D:/commerceTest/cs50-commerceM/Photo/GFPGAN/results")
os.system('{} {}'.format('python', cmd))
Here is the message I received:
Traceback (most recent call last):
File "D:\commerceTest\cs50-commerceM\Photo\GFPGAN\inference_gfpgan.py", line 98, in <module>
main()
File "D:\commerceTest\cs50-commerceM\Photo\GFPGAN\inference_gfpgan.py", line 52, in main
restorer = GFPGANer(
File "D:\commerceTest\cs50-commerceM\Photo\GFPGAN\gfpgan\utils.py", line 60, in __init__
loadnet = torch.load(model_path)
File "D:\Users\rapha\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 594, in load
with _open_file_like(f, 'rb') as opened_file:
File "D:\Users\rapha\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 230, in _open_file_like
return _open_file(name_or_buffer, mode)
File "D:\Users\rapha\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 211, in __init__
super(_open_file, self).__init__(open(name, mode))
PermissionError: [Errno 13] Permission denied: 'D:/commerceTest/cs50-commerceM/Photo/GFPGAN/experiments/pretrained_models/'
I can only guess here but the error that you are getting is because Python is trying to open a directory as a file (which won't work).
It looks like the path that you are passing in to --model_path is a directory but torch.load() expects a file, that would explain it.
I would start with understanding what exactly the script inference_gfpgan.py does and how it works.

copy2 PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

I'm copying a file to the temp dir
def uploadAvatar(self, schid, img):
try:
img = path.abspath(img)
filename = self.generateAvatarFileName(schid)
temp_dir = tempfile.gettempdir()
self.tmp = path.join(temp_dir, filename)
copy2(img, self.tmp)
#imgname = path.basename(self.tmp)
imgdir = path.dirname(self.tmp)+path.sep
self.retcode = ts3lib.createReturnCode()
(error, ftid) = ts3lib.sendFile(schid, 0, "", "/avatar/"+filename, True, False, imgdir, self.retcode);
except:
try: from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon Script", 0)
except:
try: from traceback import format_exc;print(format_exc())
except: print("Unknown Error")
and want to delete it after I uploaded it
def onServerErrorEvent(self, schid, errorMessage, error, returnCode, extraMessage):
if self.retcode == returnCode: self.setAvatar(schid, self.tmp);remove(self.tmp)
But I always get
Error calling method of plugin Dynamic Avatar Changer: Traceback (most recent call last):
File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\ts3plugin.py", line 259, in callMethod
ret.append(meth(*args))
File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\dynamicAvatar\__init__.py", line 114, in onServerErrorEvent
if self.retcode == returnCode: self.setAvatar(schid, self.tmp);remove(self.tmp)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\blusc\\AppData\\Local\\Temp\\avatar_ZFV2RGU5MjNmb0NyN3hsN1NnU3BGQzdsTFZZPQ'
How can accomplish this? Please help!
Sounds like you need to close the file or stop the process heres a link I found that my be able to solve your problem. File handling in Python - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process.

IOError: [Errno 2] No such file or directory: 'Book1.xls'

Traceback (most recent call last):
File "C:/my_python/read1.py", line 3, in <module>
book = open_workbook('Book1.xls',on_demand=True)
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 449, in open_workbook
ragged_rows=ragged_rows,
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 941, in biff2_8_load
f = open(filename, open_mode)
IOError: [Errno 2] No such file or directory: 'Book1.xls'
I am getting this error message in python while trying to open an excel sheet.....How can i solve this ?
Either make sure Book1.xls is in "C:\my_python\", which is also where your script is, or use the full path to where Bool1.xls is located. For example:
book = open_workbook('C:\\Users\\Jeeva\\Documents\\Book1.xls',on_demand=True)

IOError: [Errno 13] Permission denied in python when i read a file

i have a text file in an external HD E:
my_file = "E:\\myfolder\\myfile.txt"
lines_len = 0
for p in open(my_file , "r"):
lines_len +=1
i wish to read all line. When the file read a certain amount of line i get this message
Traceback (most recent call last):
File "<input>", line 2, in <module>
IOError: [Errno 13] Permission denied

Categories