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

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.

Related

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

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

Overwriting files in python

I know there are few threads already for the problem, but I couldnt resolve my problem. Any help will be appreciated.
I have set of files which has be replaced by the starting word.But I get this error everytime I use os.rename().I even tried using shutil.move().But it does not work
for f in os.listdir(p):
path, filename = os.path.split(f)
file_name, file_ext = os.path.splitext(f)
start, *rest = file_name.rsplit("_",1)
new_filename = '_'.join(start.split('_')[:-3])
#print(new_filename)
old_file = os.path.join(path,file_name)
new_file = os.path.join(path,new_filename)
#print(old_file)
print(new_file)
try:
os.rename(old_file, new_file)
except WindowsError:
os.remove(new_file)
os.rename(old_file, new_file)
FileNotFoundError: [WinError 2] The system cannot find the specified file: '1212_seg01_src13_cam01_meas' -> '1212'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/temp/mptAlgorithm2dPython_vc141_0.0.1_mtu/datapreprocessing.py", line 23, in <module>
os.remove(new_file)
PermissionError: [WinError 5] Access denied: '1212'

windows - PermissionError: [Errno 13] Permission denied when accessing Apache log file

Here is my code, which intends to constantly check apache log file and process the newly updated contents.
# detect.py
fp = open(r'C:\xampp\apache\logs\access.log', 'r')
...
def follow(fp):
fp.seek(0, 2)
while True:
line = fp.readline()
if not line:
time.sleep(0.0001)
continue
yield line
...
if __name__ == '__main__':
loglines = follow(fp)
for line in loglines:
data = LogParser(line, db)
...
When I run this file, I always get the following error:
Traceback (most recent call last):
File ".\core\detect.py", line 28, in <module>
for line in loglines:
File ".\core\detect.py", line 19, in follow
line = fp.readline()
PermissionError: [Errno 13] Permission denied
I have tried nearly all available means, such as: changing file privileges, running as administrators, killing all python related process before running this file ...
but I still get that error. I want to know how to deal with this problem.

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.

Insert csv file to mysql table OSError: [Errno 13] Permission denied error

I am trying to insert csv file to mysql table using sub process.call from other script but receiving this error.I don't know where am i going wrong I checked my file and everything looks fine.
def ringoCallback3(filename):
#Run the RINGO insert script
tmp = filename.split('/')
just_filename = tmp[-1]
new_filename = "/home/toor/doneringofiles/%s" % just_filename
retval = subprocess.call(["/usr/local/bin/ringo.py",filename])
os.rename(filename, new_filename)
return retval
dirlist = [ ['/home/toor/ringolist',ringoCallback3]]
while (True):
# Go through each of the directories
for mylist in dirlist:
check_dir = mylist[0]
callback = mylist[1]
# get the list of files in the directory
filelist = os.listdir(check_dir)
for this_file in filelist:
if ((this_file == ".") or (this_file == "..") or (this_file == "doneringofiles")):
print "Skipping self and parent"
continue
full_filename = "%s/%s" % (check_dir, this_file)
# Get the modification time of the file
first_stat = os.stat(full_filename)[8]
# Sleep for 1 second
time.sleep(1)
# Get the modification time again
second_stat = os.stat(full_filename)[8]
# If the modication time has not changed, then the file is stable
# and can be sent to the callback
if (first_stat == second_stat):
callback(full_filename)
# Now sleep for 30 seconds before doing the whole lot again
time.sleep(30)
When I run this code : I get this error:
Traceback (most recent call last):
File "./dirmon.py", line 80, in <module>
callback(full_filename)
File "./dirmon.py", line 44, in ringoCallback3
retval = subprocess.call(["/usr/local/bin/ringo.py",filename])
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied
This caused because /usr/local/bin/ringo.py is not executable by the user that your script is running as.
You can check this, by trying to run the script from a shell (as the same user that your script runs as):
$ /usr/local/bin/ringo.py
You either need to make it executable with the chmod command, or call the subprocess like this:
subprocess.call(["python", "/usr/local/bin/ringo.py",filename])

Categories