forked from mongodb/mongo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileops.py
74 lines (52 loc) · 1.99 KB
/
fileops.py
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
"""Utility to support file operations."""
import os
from typing import Any, Dict
import yaml
def create_empty(path):
"""Create an empty file specified by 'path'."""
with open(path, "w") as file_handle:
file_handle.write("")
def getmtime(path):
"""Return the modified time of 'path', or 0 if is does not exist."""
if not os.path.isfile(path):
return 0
return os.path.getmtime(path)
def is_empty(path):
"""Return True if 'path' has a zero size."""
return os.stat(path).st_size == 0
def get_file_handle(path, append_file=False):
"""Open 'path', truncate it if 'append_file' is False, and return file handle."""
mode = "a+" if append_file else "w"
return open(path, mode)
def write_file(path: str, contents: str) -> None:
"""
Write the contents provided to the file in the specified path.
:param path: Path of file to write.
:param contents: Contents to write to file.
"""
with open(path, "w") as file_handle:
file_handle.write(contents)
def write_file_to_dir(directory: str, file: str, contents: str, overwrite: bool = True) -> None:
"""
Write the contents provided to the file in the given directory.
The directory will be created if it does not exist.
:param directory: Directory to write to.
:param file: Name of file to write.
:param contents: Contents to write to file.
:param overwrite: If True it is ok to overwrite an existing file.
"""
target_file = os.path.join(directory, file)
if not overwrite:
if os.path.exists(target_file):
raise FileExistsError(target_file)
if not os.path.exists(directory):
os.makedirs(directory)
write_file(target_file, contents)
def read_yaml_file(path: str) -> Dict[str, Any]:
"""
Read the yaml file at the given path and return the contents.
:param path: Path to file to read.
:return: Contents of given file.
"""
with open(path) as file_handle:
return yaml.safe_load(file_handle)