Python 未定义“NameError”测试。我哪里做错了?
我正在使用Python2.7,试图让我的程序检查文件是否存在,如果存在,程序应该询问用户是否要覆盖它。如果文件不存在,则应创建一个新文件。如果发现文件存在,则重复这两个步骤。代码如下:Python 未定义“NameError”测试。我哪里做错了?,python,Python,我正在使用Python2.7,试图让我的程序检查文件是否存在,如果存在,程序应该询问用户是否要覆盖它。如果文件不存在,则应创建一个新文件。如果发现文件存在,则重复这两个步骤。代码如下: import os.path file_name = input("Please enter the name of the file to save your data to: Example: test.txt ") file_open = open(file_name, "w") if os.p
import os.path
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
print ("File exists")
decide = input("Do you want to overwrite the file?, Yes or No")
control = True
while control:
if decide != "Yes":
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
if os.path.isfile(file_name):
print ("File exists")
else:
newFile = open(file_name, "w")
newFile.write(str(model))
newFile.close()
control=False
else:
print("Creating a new file..................")
file_open.write(str(model))
file_open.close()
在第2行、第6行和第10行中,它应该是原始输入,因为您正在读取字符串,并检查代码缩进。如果我使用不同的名称,python只会突出显示该特定名称,从而导致名称错误消息Oooh可能重复感谢Tigerhawk,我忘记了版本问题!!干杯,现在就好了!if os.path.isfilefile\u name:-此行将始终返回True,因为您创建的文件名file\u name正好位于if语句之前。因此,你永远不会接触到将要创建文件的其他人。我已对输入问题进行了排序,但我的想法是检查文件是否存在,然后使用用户输入文件名创建一个新文件。只要用户键入的文件存在,并且他们选择不覆盖它,程序就必须不断要求他们提供新的文件名。如果您给出decise='No',您的代码将按照预期执行。