How can I remove all files from a folder in Python?
You can use the listdir function in the os module to get all the file names in a folder, and use the os.remove function to delete each file. Here is an example code:
import os
def delete_files_in_folder(folder):
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
delete_files_in_folder(file_path)
os.rmdir(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
folder_path = '/path/to/folder'
delete_files_in_folder(folder_path)
In this example, the function delete_files_in_folder takes a folder path as a parameter and iterates through each file and subfolder within the folder. If it is a file or symbolic link, it uses the os.unlink function to delete the file. If it is a folder, it recursively calls the delete_files_in_folder function to delete all files within the subfolders, and uses the os.rmdir function to delete the folder itself.