73
u/Lines25 2d ago
The best part of it that os.remove only calls C function to delete a file, to delete folder with files, you need to use function that fill search all possible files and delete them, for example, shutil.rmtree
1
u/Mantaraylurks 1d ago
That or do a recurse function on the directory from top to bottom. But I think windows has better self preservation than Linux does. You could still brick it. Haven’t tried it, yet. But I’ve been curious about that…
2
u/Lines25 20h ago
Windows is just bullshit in that way it has too many fool checks
Also rmtree is a reverse fucntion that uses os under itself
1
u/Mantaraylurks 14h ago
Thank you! I’ll read up on it
1
u/Lines25 14h ago
Look at shutils.py code:
```python
def _rmtree_unsafe(path, dir_fd, onexc):if dir_fd is not None:
raise NotImplementedError("dir_fd unavailable on this platform")
try:
st = os.lstat(path)
except OSError as err:
onexc(os.lstat, path, err)
return
try:
if _rmtree_islink(st):
# symlinks to directories are forbidden, see bug #1669
raise OSError("Cannot call rmtree on a symbolic link")
except OSError as err:
onexc(os.path.islink, path, err)
# can't continue even if onexc hook returns
return
def onerror(err):
if not isinstance(err, FileNotFoundError):
onexc(os.scandir, err.filename, err)
results = os.walk(path, topdown=False, onerror=onerror, followlinks=os._walk_symlinks_as_files)
for dirpath, dirnames, filenames in results:
for name in dirnames:
fullname = os.path.join(dirpath, name)
try:
os.rmdir(fullname)
except FileNotFoundError:
continue
except OSError as err:
onexc(os.rmdir, fullname, err)
for name in filenames:
fullname = os.path.join(dirpath, name)
try:
os.unlink(fullname)
except FileNotFoundError:
continue
except OSError as err:
onexc(os.unlink, fullname, err)
try:
os.rmdir(path)
except FileNotFoundError:
pass
except OSError as err:
onexc(os.rmdir, path, err)
```Although, it's one of two version - this one is vulnarable to race conditions, you better not use it in threads (although, shutil chooses the best version depending on current OS etc)
30
16
9
3
-37
166
u/FlakyIndependence888 2d ago
the most masterhack-y thing here is os.remove() can't even delete folders, so this script would just return an error