我正在尝试使用python打开文件。有两个函数,一个用于获取文件名并打开文件,第二个用于检查扩展名是否有效。检查一段时间,3个没有大写字母,数字或特殊字符的字符。
e.g。第一次传递testfile.txt会运行正常。但是如果我再次运行代码并使用test.123之类的变量进行测试然后输入testfile.txt,则进入while循环,但如果我使用test.abc,则响应是正确的。然后如果在错误输入后输入testfile.txt或任何其他正确的文件,代码会将我带回while循环。我在哪里弄错了。
def openfiles():
"""
this function to accept the file name and open it.
:rtype : object
"""
found_file = False
while not found_file:
try:
filename = input("Please provide the name of the file")
ext_check = checkFileEXT(filename)
if ext_check is True:
input_file = open(filename)
found_file = True
except IOError:
print("The requested file was not opened. Either the file name or extension was not correct. \
Please try again")
return input_file
def checkFileEXT(filename):
period = "."
index = filename.find(period)
request_file_name = False
if index == -1:
request_file_name = True
else:
provided_ext = filename[index + 1:len(filename)]
for char in provided_ext:
if char not in ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "0", "p", "q", "r", "t", "u", "v", "x", "y", "z"):
request_file_name = True
while request_file_name is True or len(provided_ext) != 3:
print("The file name provided was not correct")
openfiles()
return True
print(openfiles())
我遇到的另一个问题是断点越过了。它似乎甚至在Debug中运行代码。这将在第二次通过时发生。
答案 0 :(得分:0)
这是你的问题:
while request_file_name is True or len(provided_ext) != 3:
无法将request_file_name
设置为False
或更改provided_ext
的长度。因此,循环要么运行要么永远运行。
答案 1 :(得分:0)
检查文件的更好方法如下:
new_file = open_file()
while check_file(new_file) is False:
new_file = open_file()
print(new_file)
这减少了两个函数相互调用的复杂逻辑,并将它们相互分离。您需要对代码进行一些重新分解,因为这只显示了基本逻辑。