3 """Utilities for working with files."""
13 from typing import Optional
15 from os.path import isfile, join, exists
16 from typing import List
17 from uuid import uuid4
20 logger = logging.getLogger(__name__)
23 def remove(path: str) -> None:
24 """Deletes a file. Raises if path refers to a directory or a file
28 >>> filename = '/tmp/file_utils_test_file'
29 >>> os.system(f'touch {filename}')
31 >>> does_file_exist(filename)
34 >>> does_file_exist(filename)
41 def delete(path: str) -> None:
45 def without_extension(path: str) -> str:
46 """Remove one extension from a file or path.
48 >>> without_extension('foobar.txt')
51 >>> without_extension('/home/scott/frapp.py')
54 >>> without_extension('a.b.c.tar.gz')
57 >>> without_extension('foobar')
61 return os.path.splitext(path)[0]
64 def without_all_extensions(path: str) -> str:
65 """Removes all extensions from a path; handles multiple extensions
66 like foobar.tar.gz -> foobar.
68 >>> without_all_extensions('/home/scott/foobar.1.tar.gz')
73 path = without_extension(path)
77 def get_extension(path: str) -> str:
78 """Extract and return one extension from a file or path.
80 >>> get_extension('this_is_a_test.txt')
83 >>> get_extension('/home/scott/test.py')
86 >>> get_extension('foobar')
90 return os.path.splitext(path)[1]
93 def get_all_extensions(path: str) -> List[str]:
94 """Return the extensions of a file or path in order.
96 >>> get_all_extensions('/home/scott/foo.tar.gz.1')
102 ext = get_extension(path)
103 path = without_extension(path)
111 def without_path(filespec: str) -> str:
112 """Returns the base filename without any leading path.
114 >>> without_path('/home/scott/foo.py')
117 >>> without_path('foo.py')
121 return os.path.split(filespec)[1]
124 def get_path(filespec: str) -> str:
125 """Returns just the path of the filespec by removing the filename and
128 >>> get_path('/home/scott/foobar.py')
131 >>> get_path('~scott/frapp.txt')
135 return os.path.split(filespec)[0]
138 def get_canonical_path(filespec: str) -> str:
139 """Returns a canonicalized absolute path.
141 >>> get_canonical_path('/home/scott/../../home/lynn/../scott/foo.txt')
142 '/usr/home/scott/foo.txt'
145 return os.path.realpath(filespec)
148 def create_path_if_not_exist(path, on_error=None):
150 Attempts to create path if it does not exist. If on_error is
151 specified, it is called with an exception if one occurs, otherwise
152 exception is rethrown.
156 >>> path = os.path.join("/tmp", str(uuid.uuid4()), str(uuid.uuid4()))
157 >>> os.path.exists(path)
159 >>> create_path_if_not_exist(path)
160 >>> os.path.exists(path)
163 logger.debug(f"Creating path {path}")
164 previous_umask = os.umask(0)
167 os.chmod(path, 0o777)
168 except OSError as ex:
169 if ex.errno != errno.EEXIST and not os.path.isdir(path):
170 if on_error is not None:
175 os.umask(previous_umask)
178 def does_file_exist(filename: str) -> bool:
179 """Returns True if a file exists and is a normal file.
181 >>> does_file_exist(__file__)
184 return os.path.exists(filename) and os.path.isfile(filename)
187 def does_directory_exist(dirname: str) -> bool:
188 """Returns True if a file exists and is a directory.
190 >>> does_directory_exist('/tmp')
193 return os.path.exists(dirname) and os.path.isdir(dirname)
196 def does_path_exist(pathname: str) -> bool:
197 """Just a more verbose wrapper around os.path.exists."""
198 return os.path.exists(pathname)
201 def get_file_size(filename: str) -> int:
202 """Returns the size of a file in bytes."""
203 return os.path.getsize(filename)
206 def is_normal_file(filename: str) -> bool:
207 """Returns True if filename is a normal file.
209 >>> is_normal_file(__file__)
212 return os.path.isfile(filename)
215 def is_directory(filename: str) -> bool:
216 """Returns True if filename is a directory.
218 >>> is_directory('/tmp')
221 return os.path.isdir(filename)
224 def is_symlink(filename: str) -> bool:
225 """True if filename is a symlink, False otherwise.
227 >>> is_symlink('/tmp')
230 >>> is_symlink('/home')
234 return os.path.islink(filename)
237 def is_same_file(file1: str, file2: str) -> bool:
238 """Returns True if the two files are the same inode.
240 >>> is_same_file('/tmp', '/tmp/../tmp')
243 >>> is_same_file('/tmp', '/home')
247 return os.path.samefile(file1, file2)
250 def get_file_raw_timestamps(filename: str) -> Optional[os.stat_result]:
251 """Stats the file and returns an os.stat_result or None on error."""
253 return os.stat(filename)
254 except Exception as e:
259 def get_file_raw_timestamp(filename: str, extractor) -> Optional[float]:
260 tss = get_file_raw_timestamps(filename)
262 return extractor(tss)
266 def get_file_raw_atime(filename: str) -> Optional[float]:
267 return get_file_raw_timestamp(filename, lambda x: x.st_atime)
270 def get_file_raw_mtime(filename: str) -> Optional[float]:
271 return get_file_raw_timestamp(filename, lambda x: x.st_mtime)
274 def get_file_raw_ctime(filename: str) -> Optional[float]:
275 return get_file_raw_timestamp(filename, lambda x: x.st_ctime)
278 def get_file_md5(filename: str) -> str:
279 """Hashes filename's contents and returns an MD5."""
280 file_hash = hashlib.md5()
281 with open(filename, "rb") as f:
284 file_hash.update(chunk)
286 return file_hash.hexdigest()
289 def set_file_raw_atime(filename: str, atime: float):
290 mtime = get_file_raw_mtime(filename)
291 os.utime(filename, (atime, mtime))
294 def set_file_raw_mtime(filename: str, mtime: float):
295 atime = get_file_raw_atime(filename)
296 os.utime(filename, (atime, mtime))
299 def set_file_raw_atime_and_mtime(filename: str, ts: float = None):
301 os.utime(filename, (ts, ts))
303 os.utime(filename, None)
306 def convert_file_timestamp_to_datetime(
307 filename: str, producer
308 ) -> Optional[datetime.datetime]:
309 ts = producer(filename)
311 return datetime.datetime.fromtimestamp(ts)
315 def get_file_atime_as_datetime(filename: str) -> Optional[datetime.datetime]:
316 return convert_file_timestamp_to_datetime(filename, get_file_raw_atime)
319 def get_file_mtime_as_datetime(filename: str) -> Optional[datetime.datetime]:
320 return convert_file_timestamp_to_datetime(filename, get_file_raw_mtime)
323 def get_file_ctime_as_datetime(filename: str) -> Optional[datetime.datetime]:
324 return convert_file_timestamp_to_datetime(filename, get_file_raw_ctime)
327 def get_file_timestamp_age_seconds(filename: str, extractor) -> Optional[int]:
329 ts = get_file_raw_timestamps(filename)
332 result = extractor(ts)
336 def get_file_atime_age_seconds(filename: str) -> Optional[int]:
337 return get_file_timestamp_age_seconds(filename, lambda x: x.st_atime)
340 def get_file_ctime_age_seconds(filename: str) -> Optional[int]:
341 return get_file_timestamp_age_seconds(filename, lambda x: x.st_ctime)
344 def get_file_mtime_age_seconds(filename: str) -> Optional[int]:
345 return get_file_timestamp_age_seconds(filename, lambda x: x.st_mtime)
348 def get_file_timestamp_timedelta(
349 filename: str, extractor
350 ) -> Optional[datetime.timedelta]:
351 age = get_file_timestamp_age_seconds(filename, extractor)
353 return datetime.timedelta(seconds=float(age))
357 def get_file_atime_timedelta(filename: str) -> Optional[datetime.timedelta]:
358 return get_file_timestamp_timedelta(filename, lambda x: x.st_atime)
361 def get_file_ctime_timedelta(filename: str) -> Optional[datetime.timedelta]:
362 return get_file_timestamp_timedelta(filename, lambda x: x.st_ctime)
365 def get_file_mtime_timedelta(filename: str) -> Optional[datetime.timedelta]:
366 return get_file_timestamp_timedelta(filename, lambda x: x.st_mtime)
369 def describe_file_timestamp(filename: str, extractor, *, brief=False) -> Optional[str]:
370 from datetime_utils import describe_duration, describe_duration_briefly
372 age = get_file_timestamp_age_seconds(filename, extractor)
376 return describe_duration_briefly(age)
378 return describe_duration(age)
381 def describe_file_atime(filename: str, *, brief=False) -> Optional[str]:
382 return describe_file_timestamp(filename, lambda x: x.st_atime, brief=brief)
385 def describe_file_ctime(filename: str, *, brief=False) -> Optional[str]:
386 return describe_file_timestamp(filename, lambda x: x.st_ctime, brief=brief)
389 def describe_file_mtime(filename: str, *, brief=False) -> Optional[str]:
390 return describe_file_timestamp(filename, lambda x: x.st_mtime, brief=brief)
393 def touch_file(filename: str, *, mode: Optional[int] = 0o666) -> bool:
394 return pathlib.Path(filename, mode=mode).touch()
397 def expand_globs(in_filename: str):
398 for filename in glob.glob(in_filename):
402 def get_files(directory: str):
403 for filename in os.listdir(directory):
404 full_path = join(directory, filename)
405 if isfile(full_path) and exists(full_path):
409 def get_directories(directory: str):
410 for d in os.listdir(directory):
411 full_path = join(directory, d)
412 if not isfile(full_path) and exists(full_path):
416 def get_files_recursive(directory: str):
417 for filename in get_files(directory):
419 for subdir in get_directories(directory):
420 for file_or_directory in get_files_recursive(subdir):
421 yield file_or_directory
424 class FileWriter(object):
425 def __init__(self, filename: str) -> None:
426 self.filename = filename
428 self.tempfile = f'{filename}-{uuid}.tmp'
431 def __enter__(self) -> io.TextIOWrapper:
432 assert not does_path_exist(self.tempfile)
433 self.handle = open(self.tempfile, mode="w")
436 def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
437 if self.handle is not None:
439 cmd = f'/bin/mv -f {self.tempfile} {self.filename}'
442 raise Exception(f'{cmd} failed, exit value {ret>>8}')
446 if __name__ == '__main__':