How can I delete all files in a directory in Python?

How can I delete all files in a directory in Python?

You can loop through all files in a directory and delete them using os.remove:

import os

directory = 'path/to/your/folder'
for filename in os.listdir(directory):
    file_path = os.path.join(directory, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)

This approach works on both Windows and *nix systems, helping you delete all files in a directory with ease.

Python’s pathlib library makes it easier to handle paths and files:

from pathlib import Path

directory = Path('path/to/your/folder')
for file in directory.iterdir():
    if file.is_file():
        file.unlink()

This is a clean and Pythonic way to delete all files in a directory, and it works across different platforms.

If you want to delete everything in the directory (including subdirectories), shutil is a good choice:

import shutil

directory = 'path/to/your/folder'
for filename in os.listdir(directory):
    file_path = os.path.join(directory, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)
    elif os.path.isdir(file_path):
        shutil.rmtree(file_path)

This approach handles both files and directories, effectively helping you delete all files in a directory, and works on all platforms including Windows and *nix.