@י.-פל. @האדם-החושב יש אפשרות גם למחוק תיקיות שלמות ולא רק קבצים?
(לבנתיים מה שניסיתי היה נראה שלא)
עריכה:
למעוניינים ביקשתי מר' בינה שיוסיף שימחק גם תיקיות שלמות, ונה הקוד
import os
import shutil
def files_to_delete(list_file):
with open(list_file, "r", encoding="utf-8") as f:
content = f.read().splitlines()
for line in content:
if os.path.isdir(line):
delete_directory(line)
else:
delete_file_and_empty_folder(line)
def delete_file_and_empty_folder(file_path):
try:
# Delete the file
os.remove(file_path)
except FileNotFoundError:
print(f"File not found: {file_path}")
return
except Exception as e:
print(f"Error deleting file {file_path}: {e}")
return
# Check if the folder containing the file is empty
folder_path = os.path.dirname(file_path)
try:
if not os.listdir(folder_path):
# If the folder is empty, delete it
os.rmdir(folder_path)
except OSError:
print(f"Folder not empty or couldn't remove: {folder_path}")
def delete_directory(directory_path):
try:
shutil.rmtree(directory_path)
print(f"Directory deleted: {directory_path}")
except Exception as e:
print(f"Error deleting directory {directory_path}: {e}")
list_file = "נתיבים למחיקה.txt"
files_to_delete(list_file)