【问题标题】:Python program: reading a filePython程序:读取文件
【发布时间】: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_percentprint(open_file()) 调用 open_file(),打印返回的文件对象的表示,然后将其丢弃。
  • 哎呀!从错误处理程序中递归是一个非常的坏主意...请从open_file 中删除break 行(在return 之后无用),并从函数结束。

标签: python python-3.x


【解决方案1】:

您在一个函数中定义的变量不能从另一个函数访问。例如,要解决这个问题,您可以这样做(将返回的值存储在“主函数”变量中并将其传递给您的下一个函数):

def find_min_percent(line): 
    '''Find the min percent change in the line; return the value and the index.'''
    percent_lst = []
    # You can use f from this function, as long as you don't modify it
    line = f.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 


f = open_file()
print(f)
print (find_min_percent(line))

顺便说一句,您使用line 变量的方式很奇怪。它仅在find_min_percent 内部使用,但在函数外部定义,甚至作为参数传递。为什么?你想达到什么目的?

(请参阅here 了解有关访问函数外部定义的变量的帖子)

【讨论】:

  • 就像我在帖子末尾所说的那样,我应该编写的实际程序比这要长得多。我正在一块一块地编写代码,这是迄今为止我所得到的。我在函数之外定义它的原因是因为稍后我需要有一个 find_max_percent 和 find_gdp 来接受行字符串。
  • 这不是问题。您可以拥有一个“全局”变量ffile,您可以在模块中的任何位置访问它(只要它是在函数之外定义的)。我将编辑我的答案,以便您查看。
  • @NouraAsrar:如果你想让 2 个函数共享一个变量,最好的方法是像 Thomas 一样传递一个参数,如下所示。仅应在特殊用例中使用的另一种方法是使用全局变量。但是如果你没有在你的函数中声明它是全局的,open_file 中的file 将是一个隐藏全局变量的局部变量!如果你不明白这句话远离全局变量...
  • 在另一个不相关的点上,我有点担心我没有看到文件在任何地方关闭。处理完文件后,您应该始终关闭它。在这里,您可以在末尾添加f.close()
【解决方案2】:

返回的file变量超出函数作用域 固定代码:

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,file): 
    '''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 

temp=open_file()
print(temp)
print (find_min_percent(line,temp))

【讨论】:

    【解决方案3】:

    另一种方法:

    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')
                print('user_input: ', user_input)
                line = file.readline(9)
                file.close()
                return find_min_percent(line)
            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())
    

    请注意,我不确定您的 find_min_percent 方法的正确性。此外,如果您手动打开文件(不使用with open),您也需要显式关闭。

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 1970-01-01
      • 2015-03-23
      • 2011-01-03
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2011-07-22
      • 2020-09-20
      相关资源
      最近更新 更多