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

不打扰是莪最后的温柔 提交于 2019-11-29 11:12:19

问题


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?


回答1:


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').




回答2:


In Python 2, use:

print >>file_output, 'Fooo line '

In Python 3, use:

print('Fooo line ', file=file_output)



回答3:


I feel that it should. Nearest thing you can use is:

file_output.writelines([foo_msg, '\n'])



回答4:


print() is the function you are looking for. Like much of the core polymorphism in python, printing is provided by a built-in function instead of using methods (just like len(), next(), repr() etc!).

The print() function being the universal interface also makes it more versatile, without the file objects themselves having to implement it. In this case, it defaults to terminating by newline, but it can be chosen in the function call, for example:

print("text", file=sys.stderr, end="\n")

In your suggested use case, all file objects would have to implement not only a .write() method (now used by print()), but also .writeln(), and maybe even more! This function-based polymorphism makes python very rich, without burdening the interfaces (remember how duck typing works).

Note: This model has always been at the center of Python. It is only more pure in my examples, that pertain to Python 3




回答5:


Probably no real reason, just that it's really easy to write a newline when you need it, so why clutter up the file interface with an extra method just to do that?



来源:https://stackoverflow.com/questions/2575619/why-python-language-does-not-have-a-writeln-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!