1

I'm a beginner at python and im just trying to do some simple file I/O questions.

I wrote this code:

sentence=input("give a sentence:")
f=open("wordsOnLine.txt",'w')
f.write(sentence)
f.close

I just want a sentence that a user inputs to be saved in a text file. I was going to use that file for a different part of the question, but after running the code, inputting a test sentence, and checking the file, it's just empty. I didn't get any errors either.

Idk what im doing wrong. Any help would be appreciated. Thanks in advance.

3
  • f.close is a method so you need to give it () like so: f.close() Commented May 27, 2020 at 15:45
  • Ah thanks. IDK why i didnt catch that after looking over it so many times lol Commented May 27, 2020 at 15:47
  • @Alfie You're right, but the file would close automatically when the program exits, so that likely isn't the problem here. Commented May 27, 2020 at 15:47

1 Answer 1

2

Either add parenthesis like f.close(), or use with: (a more common approach).

sentence=input("give a sentence:")

with open("wordsOnLine.txt",'w') as f:
    f.write(sentence)

In your case,

sentence=input("give a sentence:")
f=open("wordsOnLine.txt",'w')
f.write(sentence)
f.close()
Sign up to request clarification or add additional context in comments.

1 Comment

If you're using with, you don't need close().

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.