我对使用 Python 进行编码非常陌生,非常感谢您的帮助!
努力实现:
选择输入以使用计算器或打开文件(已附加所有计算)
文件不存在使用防御编码
提示用户再次输入文件名 问题
第一个输入(process_choice)没有带我到选项
打开文件阅读:阅读文件并显示
fileNotFoundError at the same time
from pathlib import Path
file = open('calculatortextfile.txt' , 'a')
process_choice = str(input("Enter 'C' to use calculator or 'F' to open file: ")).upper
#CALCULATOR OPTION
while True:
if process_choice == "C":
try:
num1 = float(input("Please enter a number:"))
num2 = float(input("Please enter another number: "))
operator = input("Please enter the operator (+, -, *, /): ")
if operator == "+":
calculation = num1 + num2
entry = ("{} + {} = {}".format(num1,num2,calculation))
print(entry)
elif operator == "-":
calculation = num1 - num2
entry = ("{} - {} = {}".format(num1,num2,calculation))
print(entry)
elif operator == "*":
calculation = num1 * num2
entry = ("{} * {} = {}".format(num1,num2, calculation))
print(entry)
elif operator == "/":
calculation = num1 / num2
entry = ("{} / {} = {}".format(num1, num2, calculation))
print(entry)
else:
print("You have not entered a valid operator, please try again.")
continue
file.write(str(num1) + " " + operator + " " + str(num2) + " = " + str(calculation) +"\n")
choice = input("To continue enter - yes or no: ")
if choice == "no":
print("See you next time!")
break
except ValueError:
print("Wrong key entered. Please key in a number")
except ZeroDivisionError:
print("You cannot divide by zero. Please try again!")
# OPEN FILE TO READ OPTION
elif process_choice == "F":
file_name = input("Please enter the name of the file: ").lower
path = Path("calculatortextfile.txt")
contents = path.read_text()
print(contents)
if file_name == "calculatorfiletext.txt":
print("The file exists")
with open(file_name, 'r') as f:
lines = f.readlines()
print(lines)
else:
raise FileNotFoundError('No such file or directory')
print("This file does not exist")
file.close()
调用
upper
函数:你忘记了括号。
process_choice = input("Enter 'C' to use calculator or 'F' to open file: ").upper()
(我还删除了多余的
str(...)
电话。)
你的代码的问题是使用
lower
和upper
。
那些是函数,所以你需要调用它们,像这样:
process_choice = str(input("Enter 'C' to ...")).upper()
(顺便说一下,不需要 str,
input
已经返回一个字符串。)
当你不使用括号时,你分配给变量'process_choice'的实际上是一个函数。
看到这个,你可以试试:
process_choice = str(input("Enter 'C' to ...")).upper
print(process_choice)
你得到的是:
Enter 'C' to use calculator or 'F' to open file: C
<built-in method upper of str object at 0x000001C74A7090F0>
这清楚地表明你实际上做了什么。
我在这里看到的最大问题是您试图在不关闭文件的情况下打开文件两次。关注这里,
file = open('calculatortextfile.txt' , 'a')
你打开这个文件但永远不要关闭它,如果有人选择“F”然后 输入与硬编码相同的文件目录。然后会导致上述错误。
path = Path("calculatortextfile.txt")
contents = path.read_text()
print(contents)
if file_name == "calculatorfiletext.txt":
print("The file exists")
with open(file_name, 'r') as f:
lines = f.readlines()
print(lines)
您还需要修复缩进。但这应该可以解决问题。