Python Forum
deleting an empty Dir, using pathlib.Path
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
deleting an empty Dir, using pathlib.Path
#2
A directory in a filesystem may have no relationship between the number of entries inside and the "size" returned by stat. To find if a directory is empty, I would suggest one of:
  • get the contents and see if it is empty (os.listdir, os.scandir, Path.iterdir)
  • just call os.rmdir() on all of the directories, and ignore the errors. If its empty, it will be removed. If it's not empty, it won't.

Maybe:
if fel.is_dir():
    if not any(fel.iterdir()):
        fel.rmdir()
Or:
if fel.is_dir():
    try:
        fel.rmdir()
    except OSError:
        pass
tester_V likes this post
Reply


Messages In This Thread
RE: deleting an empty Dir, using pathlib.Path - by bowlofred - Jun-30-2021, 11:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  -i option changes sys.path (removes leading empty string '') markanth 6 2,072 Aug-26-2022, 09:27 PM
Last Post: markanth
  Pathlib import not working chriswrcg 9 3,891 May-29-2022, 07:37 PM
Last Post: snippsat
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,260 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  Trying to pathlib instead of os.path tester_V 4 2,553 Jun-22-2021, 04:15 AM
Last Post: tester_V
  pathlib destpath.exists() true even file does not exist NaN 9 4,769 Dec-01-2020, 12:43 PM
Last Post: NaN
  Question about if with () or without () / pathlib Tecuma 3 2,281 Apr-02-2020, 10:02 AM
Last Post: Tecuma
  pathlib hanging bluefrog 2 3,186 Sep-25-2018, 12:59 PM
Last Post: volcano63
  pathlib: resolving a path that does not exist Skaperen 6 5,613 Sep-08-2018, 12:25 AM
Last Post: Skaperen
  makin hardlinks with pathlib.Path Skaperen 2 5,300 Sep-06-2018, 07:53 AM
Last Post: scidam
  Need help using pathlib to read text file into dictionary gwilli3 4 4,257 Aug-13-2018, 06:21 PM
Last Post: gwilli3

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020