将行写入文件的正确方法? [英] Correct way to write line to file?
本文介绍了将行写入文件的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我习惯做print >>f, "hi there"
但是,似乎已弃用print >>
.推荐使用哪种方法做上面的行?
However, it seems that print >>
is getting deprecated. What is the recommended way to do the line above?
更新:
关于"\n"
的所有答案...这是通用的还是Unix专用的? IE,我应该在Windows上执行"\r\n"
吗?
Update:
Regarding all those answers with "\n"
...is this universal or Unix-specific? IE, should I be doing "\r\n"
on Windows?
推荐答案
这应该很简单:
with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')
来自文档:
在写入以文本模式打开的文件时(默认),请勿将
os.linesep
用作行终止符;在所有平台上都使用一个'\ 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.
一些有用的读物:
查看全文