3 回答

TA貢獻1900條經驗 獲得超5個贊
我知道,如果您的文件不存在并且用戶鍵入“y”,則會出現此問題。在這種情況下,您的函數應如下所示:
# Searches for any previously made EMA script file and removes it. Currently errors out if file isn't seen #
while beg == 0:
remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()
if remove == "y":
# This line will check if the file exists, if it does it will be deleted
if os.path.exists("EMA_Script.txt"):
os.remove("EMA_Script.txt")
print("File Deleted")
beg += 1
elif remove == "n":
beg += 1
else:
print("Incorrect input.")
beg += 0
如您所見,我添加了此功能,這將幫助您了解該文件是否存在,如果存在,請將其刪除。如果該文件不存在,它將簡單地繼續下一條指令,從而從循環中分離出來。os.path.exists("EMA_Script.txt")beg += 1
讓我知道這是否適合您!

TA貢獻1836條經驗 獲得超5個贊
的默認行為是在文件不存在時引發異常。如果要執行其他操作,則需要捕獲異常:open
try:
f = open("EMA_Script.txt", "a+")
except FileNotFoundError:
# your code to handle the case when the file doesn't exist (maybe open with write mode)
雖然我們在這里,但在處理文件時使用上下文是一種很好的做法,以確保它們始終處于關閉狀態 - 事實上,任何需要關閉的東西(如數據庫連接)都應該以這種方式完成。原因是上下文將確保文件已關閉,即使 介于 和 之間的某些內容引發異常也是如此。openclose
因此,與其說是這種模式:
f = open(...)
# do things with file
f.close()
您要執行以下操作:
with open(...) as f:
# do things with file

TA貢獻1775條經驗 獲得超8個贊
您可以使用 try/except 塊來捕獲 .此外,使用代替變量將清理代碼:FileNotFoundErrorbreakbeg
import os
while True:
remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()
if remove == "y":
try:
os.remove("EMA_Script.txt")
print("File Deleted")
except FileNotFoundError:
pass
break
elif remove == "n":
break
else:
print("Incorrect input.")
第二個(嵌套)循環也是如此:如果輸入正確,則中斷循環,否則繼續循環。
添加回答
舉報