forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_utils.py
More file actions
39 lines (27 loc) · 761 Bytes
/
file_utils.py
File metadata and controls
39 lines (27 loc) · 761 Bytes
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
import os
import hashlib
import ipaddress
CHUNK_SIZE = 64 * 1024
def sha256_digest_stream(path: str) -> str:
hasher = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b""):
hasher.update(chunk)
return hasher.hexdigest()
def ensure_dir(directory: str):
if not os.path.exists(directory):
os.makedirs(directory)
def is_valid_ip(ip_str):
try:
if ip_str.strip().lower() == "localhost":
return True
ipaddress.ip_address(ip_str)
return True
except ValueError:
return False
def is_valid_port(port_str):
try:
port = int(port_str)
return 1 <= port <= 65535
except ValueError:
return False