我想做一个程序,但我不知道我做错了什么

2024-10-03 09:08:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图制作一个程序,要求用户输入一个带有提示“New file name”的文件,程序应该这样工作,如果名称有任何形式和/或组合重要文档.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.

Tags: orand代码name程序txtnewthat
2条回答
    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")

如果要检查文件是否存在,可以尝试读取它。我还没测试过这个,但应该能用。你知道吗

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的答案是好的。你知道吗

相关问题 更多 >