When using the Virtual File System, what is the easiest way to remove a directory, along with all of its contents?
(I’m operating on actual files in the system, rather than virtual files, but my understanding is that this should have much effect.)
I’ve tried creating a Filename pointing to the directory, and then (presuming that “.exists()” returns “True”) calling one or both of “.rmdir()” and “.unlink()”, thus far to no avail.
I imagine that I could recursively scan through the directory and all sub-directories and remove each file one-by-one–but is there an easier way?
The Python function
rmtree() from the
shutil module does this for system paths. This should work for any files on disk. I’m not sure if any other virtual file mounts support deleting files; perhaps ramdisk mounts.
Note that the operations on the Filename class do not use the virtual file system. If you want to write your own VFS-aware version of rmtree, you have to use
VirtualFileSystem.deleteFile(), which you can use in conjunction with the
walk() function imported from
direct.stdpy.file to recursively walk the files and directories.
Ah, fair enough; that should work, I imagine–thank you!
Ah, I was under the impression that they were part of the same system.
It’s likely not a huge issue for me, as I’m not performing these operations on virtual files, as far as I’m aware (this specific case only involves non-virtual files).
However, for safety’s sake, are there any caveats to using Filename-based methods (like “exists” or “touch”) for non-virtual files? (e.g. Operating-system-specific behaviours or file-path formats.) Or does this simply mean that I can only use Filename-based methods on non-virtual files?
Filename-based methods like
fn.exists() are equivalent to using Python-provided alternatives like
os.path.exists, but you get the advantage that you don’t need to worry about converting to an OS-specific path first.
Actually, that’s not quite true: as of Python 3.6, Filename objects should work in most Python system calls (of course without supporting the VFS), so the Filename methods mostly have value for C++ code and less so for Python code nowadays. This is due to the fact that Python nowadays feeds paths through
os.fspath(fn), which we implement for Filename objects by returning the OS-specific path.
Ah, interesting, and thank you.
So the only difference then is that the VFS methods allow access to virtual files, if I understand correctly.