为什么Python语言没有writeln()方法?

sys*_*out 20 python syntax history language-design

如果我们需要为文件写一个新行,我们必须编写代码:

file_output.write('Fooo line \n')
Run Code Online (Sandbox Code Playgroud)

Python没有writeln()方法有什么理由吗?

Dan*_*ach 23

在Python 2中,使用:

print >>file_output, 'Fooo line '
Run Code Online (Sandbox Code Playgroud)

在Python 3中,使用:

print('Fooo line ', file=file_output)
Run Code Online (Sandbox Code Playgroud)


efo*_*nis 10

它被省略以提供方法的对称接口,file因为writeln()没有意义:

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

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

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

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

  • @eftinis,因为`readline`存在,你的"对称性"陈述并不真正成立.很少使用`readline`方法也不排除它在某些情况下的好处(例如可能需要读取一行或两行的解析器). (4认同)

Dan*_*eis 5

我认为应该。您可以使用的最接近的功能是:

file_output.writelines([foo_msg, '\n'])
Run Code Online (Sandbox Code Playgroud)