I am trying to do simple commands to write hello world to a file:
50 complexity:test% python2.7
Python 2.7.3 (default, Feb 11 2013, 12:48:32)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f=open("/export/home/vignesh/resres.txt","w")
>>> f.write("hello world")
>>> f.write("t".join(["hello","world"]))
This returns an empty file.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Python won’t flush the file after each write. You’ll either need to flush it manually using flush:
>>> f.flush()
or close it yourself with close:
>>> f.close()
When using files in a real program, it is recommended to use with:
with open('some file.txt', 'w') as f:
f.write('some text')
# ...
This ensures that the file will be closed, even if an exception is thrown. If you want to work in the REPL, though, you might want to stick with closing it manually, as it’ll try to read the entirety of the with before trying to execute it.
Method 2
You need to close the file:
>>> f.close()
Also, I would recommend using the with keyword with opening files:
with open("/export/home/vignesh/resres.txt","w") as f:
f.write("hello world")
f.write("t".join(["hello","world"]))
It will automatically close them for you.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0