Add time units and import constants.py.
[python_utils.git] / file_utils.py
index eb8c2c0dbe336a165068b724c4162dc3667a89bc..7cc8b632ac692d47a6f272403100c6806dc19136 100644 (file)
@@ -4,6 +4,7 @@
 
 import datetime
 import errno
+import hashlib
 import logging
 import os
 import time
@@ -48,7 +49,35 @@ def create_path_if_not_exist(path, on_error=None):
 
 
 def does_file_exist(filename: str) -> bool:
-    return os.path.exists(filename)
+    return os.path.exists(filename) and os.path.isfile(filename)
+
+
+def does_directory_exist(dirname: str) -> bool:
+    return os.path.exists(dirname) and os.path.isdir(dirname)
+
+
+def does_path_exist(pathname: str) -> bool:
+    return os.path.exists(pathname)
+
+
+def get_file_size(filename: str) -> int:
+    return os.path.getsize(filename)
+
+
+def is_normal_file(filename: str) -> bool:
+    return os.path.isfile(filename)
+
+
+def is_directory(filename: str) -> bool:
+    return os.path.isdir(filename)
+
+
+def is_symlink(filename: str) -> bool:
+    return os.path.islink(filename)
+
+
+def is_same_file(file1: str, file2: str) -> bool:
+    return os.path.samefile(file1, file2)
 
 
 def get_file_raw_timestamps(filename: str) -> Optional[os.stat_result]:
@@ -78,6 +107,33 @@ def get_file_raw_ctime(filename: str) -> Optional[float]:
     return get_file_raw_timestamp(filename, lambda x: x.st_ctime)
 
 
+def get_file_md5(filename: str) -> str:
+    file_hash = hashlib.md5()
+    with open(filename, "rb") as f:
+        chunk = f.read(8192)
+        while chunk:
+            file_hash.update(chunk)
+            chunk = f.read(8192)
+    return file_hash.hexdigest()
+
+
+def set_file_raw_atime(filename: str, atime: float):
+    mtime = get_file_raw_mtime(filename)
+    os.utime(filename, (atime, mtime))
+
+
+def set_file_raw_mtime(filename: str, mtime: float):
+    atime = get_file_raw_atime(filename)
+    os.utime(filename, (atime, mtime))
+
+
+def set_file_raw_atime_and_mtime(filename: str, ts: float = None):
+    if ts is not None:
+        os.utime(filename, (ts, ts))
+    else:
+        os.utime(filename, None)
+
+
 def convert_file_timestamp_to_datetime(
     filename: str, producer
 ) -> Optional[datetime.datetime]: