shutil.rmtree() raises exception WindowsError: Access is denied: - python

Trying to automatically delete files with a python script and i get:
Traceback (most recent call last):
Python script "5", line 8, in <module>
shutil.rmtree(os.path.join(root, d))
File "shutil.pyc", line 221, in rmtree
File "shutil.pyc", line 219, in rmtree
WindowsError: [Error 5] Access is denied: 'C:\\zDump\\TVzip\\Elem.avi'
using this
import os
import shutil
for root, dirs, files in os.walk(eg.globals.tvzip):
for f in files:
os.remove(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
for root, dirs, files in os.walk(eg.globals.tvproc):
for f in files:
os.remove(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
All is being run as administrator, any help?

While I can't comment on the Windows permissions (or lack there of), assuming you have correct perms, then an open file handle is really likely.
I just wanted to mention, shutil.rmtree will clear out any files in the directory it removes... so you can chop your algorithm in half, and stop removing files one by one.

Typically, this error comes up on Windows when the path you are trying to remove is read-only. You could try something along the lines of the below which may work:
import stat
import os
def make_dir_writable(function, path, exception):
"""The path on Windows cannot be gracefully removed due to being read-only,
so we make the directory writable on a failure and retry the original function.
"""
os.chmod(path, stat.S_IWRITE)
function(path)
if os.path.exists(path):
shutil.rmtree(path, onerror=make_dir_writable)
Documentation on the subject can be found here: https://docs.python.org/3.9/library/shutil.html#shutil.rmtree

Related

How to find and delete the corrupt files using python

I searched and found the below code which was written in python to find and delete the empty folders in the drive.
when i try to delete the folders, it is giving the error message below.
Can i have the modified code or idea to search and delete corrupt folders and files in the drive.
import os
for root, dirs, files in os.walk('//run//media//halovivek//testing'):
for file in files:
src_file = os.path.join(root, file)
if os.path.getsize(src_file) == 0:
os.remove(src_file)
dir_list = []
for root, dirs, files in os.walk('//run//media//halovivek//testing'):
dir_list.append(root)
for root in dir_list[::-1]:
if not os.listdir(root):
os.rmdir(root)
Error Message:
Traceback (most recent call last):
File "/home/halovivek/PycharmProjects/pythonProject/deleteEmpty.py", line 5, in <module>
if os.path.getsize(src_file) == 0:
File "/usr/lib/python3.9/genericpath.py", line 50, in getsize
return os.stat(filename).st_size
OSError: [Errno 5] Input/output error: '//run//media//halovivek//testing/.Trash-1000/files/Songs Folder/My Music/SAD = UNNA NENA.mp3'
Process finished with exit code 1
OSError: [Errno 5] Input/output error
In case you are running your code from a terminal, this error is likely to occur when you do not have an active stdout. To avoid issues with stdout, you may redirect the output from the terminal to a specified location as suggested here:
python my_script.py > /dev/null &

finding a string given a directory, extension, and string?

Currently, I'm trying to determine how to return a list of filenames in the directory containing a particular string...
here's how i began:
def searchABatch(directory, extension, searchString):
for file in os.listdir(directory):
if fnmatch.fnmatch(file, extension):
return file
print(searchABatch("procedural", ".py", "foil"))
I expected it to print simply the files with the extension ".py" in my "procedural" directory but I am getting the following error:
Traceback (most recent call last):
File "pitcher20aLP2.py", line 38, in <module>
print(searchABatch("procedural", ".py", "foil"))
File "pitcher20aLP2.py", line 34, in searchABatch
for file in os.listdir(directory):
FileNotFoundError: [Errno 2] No such file or directory: 'procedural'
You're trying to print contents of directory that doesn't exist in you current working directory. You should check if provided directory is actually a directory before calling os.listdir(), by using os.path.isdir()
def searchABatch(directory, extension, searchString):
if os.path.isdir(directory):
for file in os.listdir(directory):
if fnmatch.fnmatch(file, extension):
return file
print(searchABatch("procedural", ".py", "foil"))
Kevin is right, you are trying to find procedural in /home/2020/pitcher20a/procedural directory.
Check your working directory with os.getcwd() and change it needed by using os.chdir(path). Also, you can check if the directory is even a directory by using os.path.isdir() before using os.listdir().
Here is the python os module documentation - https://docs.python.org/2/library/os.html
Also, try to handle the errors gracefully.

why zipfile trying to unzip xlsx files?

I am trying to use the following code to unzip all the zip folders in my root folder; this code was found on this thread:
Unzip zip files in folders and subfolders with python
rootPath = u"//rootdir/myfolder" # CHOOSE ROOT FOLDER HERE
pattern = '*.zip'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
print(os.path.join(root, filename))
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
but I keep getting this error that says FileNotFoundError saying the xlsx file does not exist:
Traceback (most recent call last):
File "//rootdir/myfolder/Python code/unzip_helper.py", line 29, in <module>
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
File "//rootdir/myfolder/Python\Python36-32\lib\zipfile.py", line 1491, in extractall
self.extract(zipinfo, path, pwd)
File "//myaccount/Local\Programs\Python\Python36-32\lib\zipfile.py", line 1479, in extract
return self._extract_member(member, path, pwd)
File "//myaccount/Local\Programs\Python\Python36-32\lib\zipfile.py", line 1542, in _extract_member
open(targetpath, "wb") as target:
FileNotFoundError: [Errno 2] No such file or directory: '\\rootdir\myfolder\._SGS Naked 3 01 WS Kappa Coated and a very long very long file name could this be a problem i dont think so.xlsx'
My question is, why would it want to unzip this excel file anyways?!
And how can I get rid of the error?
I've also tried using r instead of u for rootPath:
rootPath = r"//rootdir/myfolder"
and I get the same error.
Any help is truly appreciated!
Some filenames and directory names may have extra dots in their names, as a consequence the last line, unlike Windows filenames can have dots on Unix:
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
this line fails. To see how that happens:
>>> filename = "my.arch.zip"
>>> root = "/my/path/to/mydir/"
>>> os.path.join(root, os.path.splitext(filename)[0])
'/my/path/to/mydir/my.arch'
With or without extra dots, problems will still take place in your code:
>>> os.path.join(root, os.path.splitext(filename)[0])
'/my/path.to/mydir/arch'
If no '/my/path.to/mydir/arch' can be found, FileNotFoundError will be raised. I suggest that you be explicit in you path, otherwise you have to ensure the existence of those directories.
ZipFile.extractall(path=None, members=None, pwd=None)
Extract all members from the archive to the current working directory. path specifies a different directory to extract to...
Unless path is an existent directory, FileNotFoundError will be raised.

Copying files into multiple directories using Python Shutil

I am trying to use shutil.copytree to copy a directory onto multiple other directories. I can't get it to work. I'm pretty sure I just need to implement ignore_errors=True, but I cant get it to work. How should I go about implementing 'ignore_errors=True' into
for CopyHere in DeleteThis:
for CopyThis in FilestoCopy:
shutil.copytree(CopyThis, CopyHere)
print('Files have been copied')
My code is as follows:
import shutil
import time
DeleteThis = ['E:', 'F:']
FilestoCopy = ['C:\\Users\\2402neha\\Desktop\\Hehe']
for Directory_to_delete in DeleteThis:
shutil.rmtree(Directory_to_delete, ignore_errors=True)
print('Directories have been wiped')
time.sleep(2)
for CopyHere in DeleteThis:
for CopyThis in FilestoCopy:
shutil.copytree(CopyThis, CopyHere)
print('Files have been copied')
Here are the error messages I get:
Traceback (most recent call last):
File "C:\Users\2402neha\OneDrive\Python\Dis Cleaner\Copy paste test.py", line 17, in <module>
shutil.copytree(CopyThis, CopyHere)
File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 309, in copytree
os.makedirs(dst)
File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\os.py", line 241, in makedirs
mkdir(name, mode)
PermissionError: [WinError 5] Ingen tilgang: 'E:'
Your destination is E:
The destination directory needs to not exist.
From the documentation for shutil.copytree:
shutil.copytree(src, dst, symlinks=False, ignore=None)
Recursively copy an entire directory tree rooted at src. The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories.
You probably want the directory name you're copying and to join it with the destination:
directory = os.path.basename(CopyThis)
destination = os.path.join(CopyHere, directory)
shutil.copytree(CopyThis, destination)

Python IOError: [Errno 2] from recursive directory call

The code below is part of a program I am writing that runs a method on every .py, .sh. or .pl file in a directory and its folders.
for root, subs, files in os.walk("."):
for a in files:
if a.endswith('.py') or a.endswith('.sh') or a.endswith('.pl'):
scriptFile = open(a, 'r')
writer(writeFile, scriptFile)
scriptFile.close()
else:
continue
When writing the program, it worked in the directory tree I wrote it in, but when I moved it to another folder to try it there I get this error message:
Traceback (most recent call last):
File "versionTEST.py", line 75, in <module>
scriptFile = open(a, 'r')
IOError: [Errno 2] No such file or directory: 'enabledLogSources.sh'
I know something weird is going on because the file is most definitely there...
You'll need to prepend the root directory to your filename
scriptFile = open(root + '/' + a, 'r')
files contains only the file names, not the entire path. The path to the file can be obtained by joining the file name and the root:
scriptFile = open(os.path.join(root, a), "r")
You might want to have a look at
https://docs.python.org/2/library/os.html#os.walk

Categories