提问人:Timmatee 提问时间:7/5/2023 更新时间:7/5/2023 访问量:14
我的问题是,当要求用户输入他们刚刚创建的文本文件的名称时,它无法识别该文件。蟒
My issue is when the user is asked to enter the name of the text file they just created, it doesn't recognise the file. Python
问:
我创建了一个计算器,它从用户那里获取输入以创建 txt。文件,一旦他们完成计算器,他们就会被要求输入他们刚刚创建的文本文件的名称来查看他们的计算。我似乎只是被用户输入文本文件以查看结果所困扰(我是 python 新手)
这是我的部分代码:
尝试:
with open(results+'.txt ', 'a') as results_file:
results_file.write(
f"\n{number_one} {maths_operation} {number_two} = {output}")
except FileNotFoundError:
print("Whoops! File not found please enter correct file name: ")
except IOError:
print("An error occured while opening the file.")
else:
raise ValueError(
"Invalid input. Please enter an operator value")
break
except ValueError:
print(
"Invalid operator! Use a valid operator '+', '-', '*', '/'. Please try again: ")
except ZeroDivisionError:
print("Whoops! You cannot divide by zero. Please try again: ")
# Conditional statements to print the results of that sum and writing it to the text file
reuse = input(
"Re-use the calculator? Type 'y' to re-use or Type 'n' to view your calculations:")
if reuse == "n":
while True:
try:
view_file = (
input("To view your calculations, please enter the filename: "))
# results_file = open('results_file', 'a')
if view_file == results_file:
results_file = open(results_file, 'r')
print(results_file.read(), "/n")
break
else:
raise FileNotFoundError(
"Whoops! File not found please enter correct file name: ")
except FileNotFoundError:
print("File not found! Please enter correct file name: ")
当我输入同名文件时,它不会打开该文件,并且由于异常处理,我最终进入了一个连续循环,要求提供正确的文件名。我不完全确定我什么时候出错了,但它肯定在这里的某个地方:
if reuse == "n":
while True:
try:
view_file = (
input("To view your calculations, please enter the filename: "))
# results_file = open('results_file', 'a')
if view_file == results_file:
results_file = open(results_file, 'r')
print(results_file.read(), "/n")
break
else:
raise FileNotFoundError(
"Whoops! File not found please enter correct file name: ")
except FileNotFoundError:
print("File not found! Please enter correct file name: ")
对我有什么建议吗?
答: 暂无答案
下一个:我的 input() 函数有问题
评论