Asked  7 Months ago    Answers:  5   Viewed   34 times

How do I delete a file or folder in Python?


  • os.remove() removes a file.

  • os.rmdir() removes an empty directory.

  • shutil.rmtree() deletes a directory and all its contents.

Path objects from the Python 3.4+ pathlib module also expose these instance methods:

  • pathlib.Path.unlink() removes a file or symbolic link.

  • pathlib.Path.rmdir() removes an empty directory.

Tuesday, June 1, 2021
answered 7 Months ago

I have seen the file system watcher fail in production and test environments. I now consider it a convenience, but I do not consider it reliable. My pattern has been to watch for changes with the files system watcher, but poll occasionally to catch missing file changes.

Edit: If you have a UI, you can also give your user the ability to "refresh" for changes instead of polling. I would combine this with a file system watcher.

Tuesday, June 1, 2021
answered 7 Months ago

You should check out Apache's commons-io. It has a FileUtils class that will do what you want.

FileUtils.deleteDirectory(new File("directory"));
Tuesday, June 1, 2021
answered 7 Months ago

No, I don't know one.

If you want to retain the original directory for some reason (ACLs, &c.), and instead really want to empty it, then you can do the following:

del /q destination*
for /d %x in (destination*) do @rd /s /q "%x"

This first removes all files from the directory, and then recursively removes all nested directories, but overall keeping the top-level directory as it is (except for its contents).

Note that within a batch file you need to double the % within the for loop:

del /q destination*
for /d %%x in (destination*) do @rd /s /q "%%x"
Sunday, August 8, 2021
answered 4 Months ago

Simplest way would be to use FileUtils.deleteDirectory from the Apache Commons IO library.

File dir = new File("root path");

Bear in mind this will also delete the containing directory.

Add this line in gradle file to have Apache

compile 'org.apache.commons:commons-io:1.3.2'  
Saturday, September 4, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :