我使用用户语音命令创建了一个记笔记程序。当文件已经存在时,我想显示一个错误。不过,当文件名不同时,它会顺利运行。当文件已经存在时,我已经编码为以写入模式打开。它将擦除以前的文件,并写入新文件,而不是在附加模式中添加。
elif 'note' in query:
try:
speak(" Okay master. what's the file name")
b= takecommand()
f = open(f"{b}.txt","w")
speak("Okay master. tell me what to note down")
a= takecommand()
f.write(f"{a}n")
f.close()
except Exception as e:
speak("file name already exist")
你能帮我排除这个脚本的故障吗?比如,当文件名相同时,我如何首先让它抛出错误?
在他们输入文件后,您需要检查文件是否存在,这可以使用"os.path.exists";正如蒂姆·罗伯茨所建议的那样。以下是应该适用于您的代码:
elif 'note' in query:
try:
Looper = True # Added a loop so it can repeatedly ask the user until they give a valid answer.
speak(" Okay master. what's the file name") # Put here instead of in the loop so it will repeat once since the else condition already asks for a new file name aswell.
while Looper == True:
b = takecommand()
if os.path.exists(f"{b}.txt"):
f = open(f"{b}.txt","w")
speak("Okay master. tell me what to note down")
a= takecommand()
f.write(f"{a}n")
Looper = False # So the loop won't repeat again (regardless of the below line).
f.close()
else:
speak("That file already exists. Give me a new file name.")
except Exception as e:
speak("Hm, an error occured. Try again later.")
我还为您添加了一个while循环,这样,如果用户提供了一个已经存在的文件名,它将一直询问,直到他们提供有效的文件名。
通过在代码顶部添加以下内容,确保导入了操作系统以使代码正常工作:
import os
使用模式'x'
x'创建一个新文件并打开它进行写入。"x"模式表示"w"如果文件已经存在,则引发FileExistsError。
try:
# ...
f = open(f"{b}.txt","x")
# ...
except FileExistsError:
speak("file name already exist")
或者使用模式"a"将字符串附加到现有文件中。
'a'打开进行写入,如果存在,则附加到文件末尾