forked from Mrinank-Bhowmick/python-beginner-projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
52 lines (42 loc) · 1.35 KB
/
main.py
File metadata and controls
52 lines (42 loc) · 1.35 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
import hashlib
import sys
from collections import defaultdict
from pathlib import Path
def get_checksum(data: bytes) -> str:
"""Return hexadecimal digest of data as a string."""
return hashlib.md5(data).hexdigest()
def get_duplicates(directory: Path) -> dict[str, list[Path]]:
"""
Return dictionary of hashes to matching file paths.
Search directory recursively.
"""
files: defaultdict[str, list[Path]] = defaultdict(list)
for child in directory.iterdir():
if child.is_dir():
files.update(get_duplicates(child))
else:
files[get_checksum(child.read_bytes())].append(child)
return files
def main() -> None:
"""
Search directory specified on command-line for duplicates.
If no directory is specified, search current directory.
"""
try:
directory = sys.argv[1]
except IndexError:
directory = "."
duplicates = get_duplicates(Path(directory))
for paths in duplicates.values():
if len(paths) == 1:
continue
for n, path in enumerate(paths):
print(f"{n}. {path}")
try:
delete = map(int, input("Delete? (e.g. 0,1,3) ").split(","))
for num in delete:
paths[num].unlink()
except (ValueError, IndexError):
continue
if __name__ == "__main__":
main()