Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic success check to write_file() and use atomic file-replacing function #161

Merged
merged 2 commits into from
Dec 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions modules/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
from modules.pokemon import Pokemon


def read_file(file: Path) -> str:
def read_file(file: Path) -> str | None:
"""
Simple function to read data from a file, return False if file doesn't exist
:param file: File to read
:return: File's contents (str)
:return: File's contents (str) or None if any kind of error occurred
"""
try:
if os.path.exists(file):
Expand Down Expand Up @@ -38,11 +38,13 @@ def write_file(file: Path, value: str, mode: str = "w") -> bool:
if not os.path.exists(directory):
os.makedirs(directory)
with open(tmp_file, mode=mode, encoding="utf-8") as save_file:
save_file.write(value)
if os.path.exists(file):
os.remove(file)
os.rename(tmp_file, file)
return True
characters_written = save_file.write(value)
if characters_written == len(value):
os.replace(tmp_file, file)
return True
else:
print(f"Writing {file} failed: Only {characters_written} out of {len(value)} characters written.")
return False
except:
return False

Expand Down