Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Python language does not have a writeln() method?

Tags:

If we need to write a new line to a file we have to code:

file_output.write('Fooo line \n') 

Are there any reasons why Python does not have a writeln() method?

like image 755
systempuntoout Avatar asked Apr 04 '10 19:04

systempuntoout


2 Answers

In Python 2, use:

print >>file_output, 'Fooo line ' 

In Python 3, use:

print('Fooo line ', file=file_output) 
like image 125
Daniel Stutzbach Avatar answered Oct 05 '22 12:10

Daniel Stutzbach


It was omitted to provide a symmetric interface of the file methods and because a writeln() would make no sense:

  • read() matches write(): they both operate on raw data
  • readlines() matches writelines(): they both operate on lines including their EOLs
  • readline() is rarely used; an iterator does the same job (except for the optional size param)

A writeline() (or writeln()) would be essentially the same as write(), since it wouldn't add an EOL (to match the behavior of writelines()).

The best way to mimic a print to a file is to use the special print-to-file syntax of Python 2.x or the file keyword argument of the print() function, like Daniel suggested.

Personally, I prefer the print >>file, ... syntax over file.write('...\n').

like image 32
efotinis Avatar answered Oct 05 '22 10:10

efotinis