0

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.

Thanks to everyone who reads and tries to answer this. Your time is greatly appreciated =).

5
  • 4
    You haven't indented properly. Commented Apr 12, 2017 at 17:38
  • 1
    Is the code you show a direct copy-paste of the actual code? With the indentation as shown? Commented Apr 12, 2017 at 17:38
  • Sorry, that was a mistake in writing it on the website. The indents are correct in the real program. I've fixed them now. Commented Apr 12, 2017 at 17:40
  • 1
    Your parameter for the function can't be written as a string. Commented Apr 12, 2017 at 17:41
  • One other thing to know is that when using the context handler with open(my_file ... you don't need to call my_file.close() at the end. It's automatically handled by the with statement! Commented Apr 12, 2017 at 17:42

2 Answers 2

9

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")
Sign up to request clarification or add additional context in comments.

2 Comments

@ZaurNasibov - fixed, and commented out file.close()
@Bob14 - please consider accepting this answer if this works for you.
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.

No need of filename.close() as "with" operator handles it automatically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.