【问题标题】:Syntax error when defining function定义函数时的语法错误
【发布时间】:2017-04-12 17:37:14
【问题描述】:

定义此函数时出现语法错误。

def questionfilehandler("filename.txt"):
    with open("filename.txt", "r") as file:
        print(file.read)
        return input()
        file.close()

我查了语法,一切似乎都是正确的。
This is the error message I got
And this is the code with the error highlighted by IDLE.

感谢所有阅读并尝试回答此问题的人。非常感谢您的时间 =)。

【问题讨论】:

  • 你没有正确缩进。
  • 您显示的代码是实际代码的直接复制粘贴吗?如图所示的缩进?
  • 对不起,在网站上写错了。缩进在实际程序中是正确的。我现在已经修好了。
  • 你的函数参数不能写成字符串。
  • 要知道的另一件事是,当使用上下文处理程序with open(my_file ... 时,您不需要在最后调用my_file.close()。它由with 语句自动处理!

标签: python function syntax


【解决方案1】:

假设你的缩进得到修复,这很明显......你不能直接调用一个字符串作为函数参数。你需要一个变量:

def questionfilehandler(filename):
    with open(filename, "r") as file:
        print(file.read())
        return input()
        # file.close() - not needed

那么……你可以用字符串作为参数调用函数:

questionfilehandler("filename.txt")

【讨论】:

  • @ZaurNasibov - 修复并注释掉 file.close()
  • @Bob14 - 如果这对你有用,请考虑接受这个答案。
【解决方案2】:
def questionfilehandler(filename = "data.txt"): # filename has default value so it will take your input if you provide with function call.
    with open(filename) as filedata:
        # print(file.read()) # no need for this method as all work done by "open()".
        for data in filedata:
            print data

questionfilehandler() # You can pass file name if you want to else keep the default.

不需要filename.close(),因为“with”操作符会自动处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2014-05-24
    相关资源
    最近更新 更多