我正在尝试创建一个程序,询问用户文件输入,提示“新文件名”,程序应该像这样工作,如果名称有任何形式和/或组合“importantdocument.text”和我尝试新的表单,如何使代码工作更容易,而不是继续{variable} != {form of importantdocumant.txt}
任何人都可以帮助看看我做错了什么或编写一个代码来执行该程序应该做什么?提前谢谢。
我的计划
a = input('New file name: ')
if a != 'ImportantDocument.txt' and a != 'importantDOCUMENT.txt' and a != 'IMPORTANTDOCUMENT.TXT' and a != 'importantdocument.txt' and a != '':
print('That name is allowed.')
elif a == 'ImportantDocument.txt' or a == 'importantDOCUMENT.txt' or a == 'IMPORTANTDOCUMENT.TXT' or a == 'importantdocument.txt':
print('That file already exists.')
程序应该输出什么
New file name: lessimportantdocument.txt
This name is allowed.
或
New file name: ImPorTaNtdoCumenT.tXt
That file already exists.
答案 0 :(得分:0)
a = input('New file name: ')
k = a.upper()
if k != 'IMPORTANTDOCUMENT.TXT':
print("That name is allowed")
if k == 'IMPORTANTDOCUMENT.TXT':
print("That file already exists")
答案 1 :(得分:0)
如果您想检查文件是否存在,可以尝试阅读。我没有对此进行过测试,但它应该有效。
file_location = 'C:/Folder/' + a
try:
with open(file_location , "r") as f:
f.read()
except IOError:
print("That file already exists")
else:
print("That name is allowed")
如果你真的只是想要破坏你目前的代码,那么Mohd的回答是好的。