为什么Python语言没有writeln()方法? [英] Why Python language does not have a writeln() method?

查看:353
本文介绍了为什么Python语言没有writeln()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果需要在文件中写新行,则必须编写代码:

file_output.write('Fooo line \n')

为什么没有Python没有writeln()方法的原因?

解决方案

为提供file方法的对称接口而被省略了,因为writeln()毫无意义:

  • read()匹配write():它们都对原始数据进行操作
  • readlines()匹配writelines():它们都在包括EOL在内的行上运行
  • readline()很少使用;迭代器执行相同的工作(可选的size参数除外)

writeline()(或writeln())与write()基本相同,因为它不会添加EOL(以匹配writelines()的行为).

模仿print到文件的最佳方法是使用Python 2.x的特殊打印到文件语法或print()函数的file关键字参数,如Daniel所建议的. /p>

就我个人而言,我更喜欢print >>file, ...语法而不是file.write('...\n').

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?

解决方案

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

这篇关于为什么Python语言没有writeln()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆