1

can someone tell me why in python 3.4.2 when I try

import codecs
f = codecs.open('/home/filename', 'w', 'utf-8') 
print ('something', file = f) 

it gives me an empty file?

Previously it was working well, but only suddenly it stopped printing to file

3
  • file= needs to be a file object. How do you create that file object? Commented Mar 1, 2015 at 0:01
  • We cannot tell you why because you need to show us a) how you are opening the file, b) how you are closing or otherwise flushing the buffers of the file and c) how you are checking that the file is empty. Commented Mar 1, 2015 at 0:03
  • Why are you using codecs.open() when the built-in open() function works far better? Commented Mar 1, 2015 at 0:14

1 Answer 1

3

File writing is buffered to avoid hitting the performance drain that is writing to a disk. Flushing the buffer takes place when you reach a threshold, flush explicitly or close the file.

You have not closed the file, did not flush the buffer, and haven't written enough to the file to auto-flush the buffer.

Do one of the following:

  • Flush the buffer:

    f.flush()
    

    This can be done with the flush argument to print() as well:

    print('something', file=f, flush=True)
    

    but the argument requires Python 3.3 or newer.

  • Close the file:

    f.close()
    

    or use the file as a context manager (using the with stamement):

    with open('/home/filename', 'w', encoding='utf-8') as f:
         print('something', file=f)
    

    and the file will be closed automatically when the block is exited (on completion, or an exception).

  • Write more data to the file; how much depends on the buffering configuration.

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.