gman1230321
gman1230321

Reputation: 103

Why can't i write to a file in python 3?

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?

Upvotes: 1

Views: 37

Answers (1)

jmd_dk
jmd_dk

Reputation: 13120

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.

Upvotes: 1

Related Questions