3

What's the best way to delete all files and dirs inside a folder without deleting the folder itself using python? Using:

if os.path.exists("path/to/folder"):
    shutil.rmtree("path/to/folder/*")

Won't to the trick since the rmtree() doesn't understand UNIX style (/*). rmtree itself is fine, but it deleted the folder too, which I don't need.

kreishna
  • 31
  • 5

1 Answers1

-1

You could just recreate the folder after you delete it.

import os
path = "/home/zach/Desktop"
filename = "django"
if os.path.exists(path):
    os.system("cd %s" %path)
    os.system("rm -rf %s" %filename)
    print("deleted file")
    os.system("mkdir %s" %filename)
    print("created file")
else:
    print("error")
thesonyman101
  • 791
  • 7
  • 16
  • seems mixed up *file* and *folder*. The code does not check whether the path is a file or a folder. – Raptor Jul 05 '21 at 09:12