定义函数时出现语法错误

2024-10-01 00:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

当我定义这个函数时有一个语法错误。在

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.

感谢每一位阅读并试图回答这个问题的人。非常感谢您的时间。在


Tags: the函数txt定义isdefaswith
2条回答

假设你的压痕是固定的,这很明显。。。不能将字符串作为函数参数直接调用。你需要一个变量:

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

然后。。。可以使用字符串作为参数调用函数:

^{pr2}$
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.

不需要文件名.close()作为“with”运算符自动处理。在

相关问题 更多 >