将行写入文件的正确方法?

2024-04-20 11:43:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我习惯做print >>f, "hi there"

然而,似乎print >>被弃用了。上面这一行的推荐方法是什么?

更新: 关于所有这些答案,"\n"…这是通用的还是Unix特有的?我应该在Windows上做"\r\n"吗?


Tags: 方法答案windowsunixhithereprint习惯
3条回答

python docs建议这样做:

with open('file_to_write', 'w') as f:
    f.write('file contents')

所以我通常就是这样做的:)

来自docs.python.org的语句:

It is good practice to use the 'with' keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.

这应该简单到:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

从文档中:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

一些有用的阅读:

您应该使用Python 2.6+之后提供的print()函数

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

对于Python 3,您不需要import,因为print()函数是默认的。

另一种方法是:

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

引用Python documentation中有关换行符的内容:

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

相关问题 更多 >