我应该编写一个程序,它不断地向用户提供一个文件名,直到它输入正确的文件名为止。然后,find_min_percent应该接受一个参数,GDP.txt文件中的一行(str)然后遍历该行以找到最小值并返回该值。这里是我的代码到目前为止Python程序:读取文件
line = " "
def open_file():
''' Repeatedly prompt until a valid file name allows the file to be opened.'''
while True:
user_input = input('Enter a file name: ')
try:
file = open(user_input, 'r')
return file
break
except FileNotFoundError:
print('Error. Please try again')
open_file()
def find_min_percent(line):
'''Find the min percent change in the line; return the value and the index.'''
percent_lst = []
line = file.readline(9)
percent_lst += [line]
percent_int = [float(i) for i in percent_lst]
min_value = 10000
for percent in percent_int:
if percent < min_value:
min_value = percent
return min_value
print(open_file())
print (find_min_percent(line))
我的问题是与readline()。它说变量文件是未定义的。此代码的大纲不包含“def find_min_percent(line):”部分中的文件。所以我不知道如何去解决这个问题。我也不能在函数之外设置行,因为我必须在程序的其他函数中使用相同的行变量来读取其他行。所以我不知道该怎么做才能保持不变
为什么不保存'open_file()'的返回值并将它传递给'find_min_percent'? 'print(open_file())'调用'open_file()',打印返回的文件对象的表示形式,然后抛弃它。 –
Oups!从一个错误处理程序递归是一个非常糟糕的主意......请从'open_file'中删除'break'行(在'return'之后无用),并从结尾删除糟糕的'open_file'行功能。 –