定义此函数时出现语法错误。
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.
感谢所有阅读并试图回答此问题的人。非常感谢您的时间=)。
答案 0 :(得分:9)
假设您的缩进得到修复,这很明显......您不能直接将字符串作为函数参数调用。你需要一个变量:
def questionfilehandler(filename):
with open(filename, "r") as file:
print(file.read())
return input()
# file.close() - not needed
然后......你可以用字符串作为参数来调用函数:
questionfilehandler("filename.txt")
答案 1 :(得分:0)
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”操作符自动处理它。