将行写入文件的正确方法? [英] Correct way to write line to file?

查看:51
本文介绍了将行写入文件的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯做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.

一些有用的读物​​:

  • with语句
  • open()
    • 'a'用于追加或使用
    • 'w'会被截断
    • The with statement
    • open()
      • 'a' is for append, or use
      • 'w' to write with truncation

      这篇关于将行写入文件的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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