28 lines
1.1 KiB
Plaintext
28 lines
1.1 KiB
Plaintext
###############################################
|
|
Prompt to Kiro AI (Default):
|
|
|
|
from now on, I will mostly be asking questions about approach, so please do not perform any actions or code edits unless explicitly requested. also, please be less verbose - I want nice, quick answers that provide the necessary context. How can I check if a file exists/isreadable for my loadSave function?
|
|
|
|
Response:
|
|
|
|
Two clean options:
|
|
|
|
os.path.exists(path) — checks the file is there before opening.
|
|
|
|
python
|
|
|
|
import os
|
|
if os.path.exists(path):
|
|
# open and read
|
|
try/except — just attempt to open and catch the failure. This is the more Pythonic approach and also handles the "exists but unreadable/corrupt" case in one shot:
|
|
|
|
python
|
|
|
|
try:
|
|
with open(path) as f:
|
|
...
|
|
except (FileNotFoundError, IOError):
|
|
return defaultState()
|
|
For loadSave, the try/except is the better fit since you also want to catch bad JSON — wrap json.load in the same block and catch json.JSONDecodeError too, falling back to a fresh default state on any failure.
|
|
|
|
############################################### |