-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisk_cleanup.py
More file actions
executable file
·126 lines (110 loc) · 4.59 KB
/
Copy pathdisk_cleanup.py
File metadata and controls
executable file
·126 lines (110 loc) · 4.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
import os
import sys
import subprocess
import time
def clear_full_directories(directories, automatic_cleaning):
for directory, usage_percentage in directories:
if str(usage_percentage).endswith('%'):
usage_percentage = float(usage_percentage[:-1])
if usage_percentage >= 100:
if automatic_cleaning:
clear_directory(directory)
else:
print(f"\nDirectory: {directory} is full. Clear it? (y/n): ")
confirmation = input()
if confirmation.lower() == "y":
clear_directory(directory)
else:
print(f"\nSkipping directory: {directory}")
def clear_directory(path):
now = time.time()
deleted_files = []
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
try:
if os.path.getmtime(file_path) < (now - 30 * 86400):
deleted_files.append(file_path)
print(f"File marked for deletion: {file_path}")
except FileNotFoundError:
print(f"File not found: {file_path}")
if not os.access(path, os.W_OK):
print("The directory is read-only. Unable to delete files.")
return
if len(deleted_files) == 0:
print("No files marked for deletion.")
return
confirmation = input(f"\nDo you want to delete {len(deleted_files)} file(s)? (y/n): ")
if confirmation.lower() == "y":
for file_path in deleted_files:
try:
os.remove(file_path)
print(f"Deleted file: {file_path}")
except Exception as e:
print(f"Failed to delete file: {file_path}. Error: {str(e)}")
else:
print("Cleanup aborted.")
def display_disk_space():
df_output = subprocess.check_output(['df', '-h']).decode('utf-8')
print("Disk space information:\n")
print(df_output)
lines = df_output.strip().split('\n')
if len(lines) < 2:
print("Unable to retrieve disk space information.")
sys.exit(1)
# Extracting the directory paths and percentages
directories = []
for line in lines[1:]:
parts = line.split()
directory_path = parts[5]
usage_percentage = parts[4]
directories.append((directory_path, usage_percentage))
return directories
if __name__ == "__main__":
print("Disk space before cleanup:")
directories = display_disk_space()
print("\nDirectories with high disk usage:")
high_usage_directories = []
for directory, usage_percentage in directories:
if str(usage_percentage).endswith('%'):
usage_percentage = float(usage_percentage[:-1])
if usage_percentage >= 100:
high_usage_directories.append((directory, usage_percentage))
print(f"{directory}: {usage_percentage}%")
if len(high_usage_directories) == 0:
print("\nNo directories with high disk usage.")
sys.exit(0)
automatic_cleaning = input("\nDo you want to automatically clean the full directories? (y/n): ")
if automatic_cleaning.lower() == "y":
clear_full_directories(high_usage_directories, True)
else:
print("\nClearing directories manually:")
while True:
manual_directory = input("Enter the directory path to clean (or 'q' to quit): ")
if manual_directory.lower() == 'q':
sys.exit(0)
if os.path.isdir(manual_directory):
if os.access(manual_directory, os.W_OK):
clear_directory(manual_directory)
break
else:
print("The directory is read-only. Unable to delete files.")
else:
print("Invalid directory path.")
continue
now = time.time()
deleted_files = []
for root, dirs, files in os.walk(manual_directory):
for file in files:
file_path = os.path.join(root, file)
try:
if os.path.getmtime(file_path) < (now - 30 * 86400):
deleted_files.append(file_path)
print(f"File marked for deletion: {file_path}")
except FileNotFoundError:
print(f"File not found: {file_path}")
if len(deleted_files) == 0:
print("No files marked for deletion.")
print("\nDisk space after cleanup:")
display_disk_space()