[英]Syntax error when defining function
I've got a syntax error when defining this function. 定义此函数时出现语法错误。
def questionfilehandler("filename.txt"):
with open("filename.txt", "r") as file:
print(file.read)
return input()
file.close()
I've looked up the syntax, and it all appears to be correct. 我查了一下语法,这一切似乎都是正确的。
This is the error message I got 这是我收到的错误消息
And this is the code with the error highlighted by IDLE. 这是带有IDLE突出显示的错误的代码。
Thanks to everyone who reads and tries to answer this. 感谢所有阅读并尝试回答此问题的人。 Your time is greatly appreciated =).
非常感谢您的时间=)。
Assuming your indentation gets fixed, which is obvious... you cannot call a string directly as a function argument. 假设您的缩进是固定的,这很明显……您不能直接将字符串作为函数参数调用。 You need a variable:
您需要一个变量:
def questionfilehandler(filename):
with open(filename, "r") as file:
print(file.read())
return input()
# file.close() - not needed
Then... you can call the function with a string as its argument: 然后...您可以使用字符串作为参数来调用该函数:
questionfilehandler("filename.txt")
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.
No need of filename.close() as "with" operator handles it automatically. 不需要filename.close(),因为“ with”运算符会自动处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.