Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

How can I delete the contents of a local folder in Python?

The current project is for Windows, but I would like to see *nix also.

1 Answer

0 votes
by (106k points)

To delete the contents of a folder in Python you can use the os.path.join() method.

import os, shutil

folder = '/path/to/folder'

for the_file in os.listdir(folder):

   file_path = os.path.join(folder, the_file)

try:

  if os.path.isfile(file_path):

       os.unlink(file_path)

 elif os.path.isdir(file_path):

      shutil.rmtree(file_path)

except Exception as e:

      print(e)

You can also delete the contents of a folder in Python by using the shutil module:-

import shutil

shutil.rmtree('/path/to/folder')

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...