Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 代码问题-文件打开_Python_Python 3.x - Fatal编程技术网

Python 代码问题-文件打开

Python 代码问题-文件打开,python,python-3.x,Python,Python 3.x,我试图定义一个函数,该函数应该以给定的名称打开文件,在屏幕上显示其内容,一次显示三个字符,然后关闭文件。如果使用无效文件名调用此版本函数,则该函数将崩溃。但是,我认为我的代码中有一个bug,它导致代码在没有运行函数的情况下崩溃 这是我目前的代码: def trigram_printer(filename): """str -> none""" print("Please enter a filename: ") filename = input("> ")

我试图定义一个函数,该函数应该以给定的名称打开文件,在屏幕上显示其内容,一次显示三个字符,然后关闭文件。如果使用无效文件名调用此版本函数,则该函数将崩溃。但是,我认为我的代码中有一个bug,它导致代码在没有运行函数的情况下崩溃

这是我目前的代码:

def trigram_printer(filename):
    """str -> none"""
    print("Please enter a filename: ")
    filename = input("> ")
    while True:
        try:
            file = open(filename)
            for line in file:
                print(line)
            file.close()
            break
        except IOError:
            print("There was a problem accessing file '" + filename + "'." + \
                  "Please enter a different filename.")
            filename = input(">")
对于错误消息,我实际上得到了“访问文件时出现问题”'+filename+“'.”\
“请输入其他文件名。”。。。因此,我认为它可能至少起了一点作用。如果可以,请帮助我…

您必须缩进所有函数体

def trigram_printer(filename):
  """str -> none"""
  print("Please enter a filename: ")
  filename = input("> ")
  while True:
    try:
        file = open(filename)
        for line in file:
            print(line)
        file.close()
        break
    except IOError:
        print("There was a problem accessing file '" + filename + "'." + \
              "Please enter a different filename.")
        filename = input(">")

您正在覆盖传递给函数的文件名参数,并向用户询问文件名,所以根本不需要这样做

如前所述,您不应该使用文件,因为它是内置的,但在Python3中这不是问题

关于你的任务,我将:

  • 询问文件名
  • 打开文件
  • 读取3个字符,但不返回“”
  • 打印3个字符,或者做任何你想做的事情
  • 返回
  • 以下是我的例子:

    def trigram_printer2():
        """str -> none"""
        print("Please enter a filename: ")
        filename = input("> ")
        try:
            opened_file = open(filename)
            three_chars = opened_file.read(3)
            while three_chars != "":
                three_chars = opened_file.read(3)
                print (three_chars)
            opened_file.close()
        except IOError:
            print("There was a problem accessing file '" + filename + "'." + \
                  "Please enter a different filename.")
    

    缩进,你需要在函数的作用域中格式化你的代码。好吧,如果你得到一个IOError,查一下堆栈跟踪,看看最初的错误是什么。或者,如果它没有显示,则引发异常,而不是捕获异常。为什么要将参数filename传递给函数,然后获取filename变量的输入。您可能正在覆盖它。
    除了IOError as e:print(e)
    将提供更多信息,因为PAVOLC已注释传递一个您从未使用过的参数是多余的,如果您想使用传入的文件名删除第一个输入,该函数应该做什么?您想让用户输入文件名,然后您想打印出文件的内容,然后从函数返回吗?