1

When I run,

Text = "Hello"
newFileName = (input("What would you like to name this file? "))
newFile = open(newFileName, 'w')
newFile.write(Text)
print("Saved as ", newFileName, "!")

It makes the file. However the file is empty. Does anyone know whats wrong here?

1
  • it's not empty for me, can you write what exactly did you type in input? also prefer with open(newFileName, 'w') as f: since it handles closing the file and etc. Commented Sep 25, 2018 at 18:01

1 Answer 1

1

You have to close the file object newFile, otherwise the buffer that you are really writing to when you call newFile.write() might not get flushed to the actual file on disk. That is, add this line at the end:

newFile.close()

Python has a nice construct for dealing with this "setting up and tearing down" logic, known as context managers, used by the with statement. Using this, you can change your code to

Text = "Hello"
newFileName = input("What would you like to name this file? ")
with open(newFileName, 'w') as newFile:
    newFile.write(Text)
print("Saved as ", newFileName, "!")

When the with block is done, the file is automatically closed, even if some error happens in the middle.

Sign up to request clarification or add additional context in comments.

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.