【发布时间】:2017-11-01 13:14:47
【问题描述】:
我应该为一个程序编写代码,该程序会不断地向用户询问文件名,直到输入正确的文件名。然后 find_min_percent 应该采用一个参数,即 GDP.txt 文件中的一行 (str),然后遍历该行以找到最小值并返回该值。到目前为止,这是我的代码
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(),打印返回的文件对象的表示,然后将其丢弃。 -
哎呀!从错误处理程序中递归是一个非常的坏主意...请从
open_file中删除break行(在return之后无用),并从函数结束。
标签: python python-3.x