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

标签 python file-io

如何在现代 Python 中将一行写入文件?我听说这已被弃用:

print >>f, "hi there"

另外,"\n" 是否适用于所有平台,或者我应该在 Windows 上使用 "\r\n" 吗?

最佳答案

这应该很简单:

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 - 将行写入文件的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6159900/

相关文章:

python - Pandas:从 df 的列中的值中删除第一个和最后一个元素

c++ - 读取文件直到空行

python - 如何使用scrapy限制spider爬取某些xPath

Python音频信号分类MFCC特征神经网络

python - 如何在多行前添加制表符或空格

c - 使用 read() 逐字节读取文件

java文件处理和异常

linux - 在内核 block I/O 层拦截数据

ruby - 在 Ruby 中如何检测文件是否可写?

python - 如何将 tkinter Scale 小部件 slider 的默认值设置为 100?