22

I am trying to do simple commands to write "hello world" to a file:

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.

3
  • 4
    You need f.close(). Time to learn the with statement. Commented Aug 4, 2013 at 23:40
  • 5
    I don't think this should be downvoted. The OP explained his problem sufficiently, showed his code, and asked a real question. Just because he isn't familiar with Python isn't a reason to punish him. Commented Aug 4, 2013 at 23:51
  • 1
    @Keyser - Well, I guess you could say that. Oh well, now this question is on SO for any future coders in their research. :) Commented Aug 4, 2013 at 23:58

2 Answers 2

29

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.

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

Comments

7

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.

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.