sss
sss

Reputation: 1347

Print to an empty file in python 3

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

Upvotes: 1

Views: 126

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121544

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.

Upvotes: 3

Related Questions