问题
执行while循环以验证文件扩展名。如果文件扩展名不是.exe或.bat,请再次询问用户输入。我正在寻找一种不使用import
endswith
break
函数的解决方案。
码
format = " "
while file[:-4] != ".bat" and file[:-4] != ".exe":
format = input("Enter file you like to open: ")
if format[:-4] == ".bat" or format[:-4] == ".exe":
callFunction(format)
else:
file = input("Enter file you like to open: ")
答案 0 :(得分:3)
要关注Asking the user for input until they give a valid response并使用os.path.splitext()
提取文件扩展名:
SELECT dbo.RoundUp(350.00/24, 2)
没有import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
while True:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
if extension in ALLOWED_EXTENSTIONS:
break
with open(filename) as f:
# do smth with f
:
break
没有import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
extension = None
while extension not in ALLOWED_EXTENSTIONS:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
with open(filename) as f:
# do smth with f
且没有任何导入:
break
没有ALLOWED_EXTENSTIONS = (".bat", ".exe")
filename = ""
while not filename.endswith(ALLOWED_EXTENSTIONS):
filename = input("Enter file you like to open: ")
with open(filename) as f:
# do smth with f
且没有任何导入且没有break
:
endswith()
答案 1 :(得分:1)
您不需要循环
def ask_exe(prompt='Executable file name? '):
name = input(prompt)
if name[-4:] in {'.exe', '.bat'}: return name
return ask_exe(prompt='The name has to end in ".exe" or ".bat", please retry: ')
[没有休息,没有进口,几乎没有代码...]
正如ShadowRanger所述,我的代码使用set
表示法进行成员资格测试,对于3.2之前的Python版本来说是次优的。对于使用tuple
的这些旧版本,可以避免在每次执行函数时在运行时计算集合。
...
# for python < 3.2
if name[-4:] in ('.exe', '.bat'): return name
...