Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

python - 将行写入文件的正确方法?(Correct way to write line to file?)

I'm used to doing print >>f, "hi there"

(我习惯于print >>f, "hi there")

However, it seems that print >> is getting deprecated.

(但是,似乎print >>已被弃用。)

What is the recommended way to do the line above?

(推荐使用哪种方法进行上述操作?)

Update) : Regarding all those answers with "\n" ...is this universal or Unix-specific?

(更新) :关于所有带有"\n"答案...这是通用的还是Unix专用的?)

IE, should I be doing "\r\n" on Windows?

(IE,我应该在Windows上执行"\r\n"吗?)

  ask by Yaroslav Bulatov translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should be as simple as:

(这应该很简单:)

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

From The Documentation:

(从文档:)

Do not use os.linesep as a line terminator when writing files opened in text mode (the default);

(写入以文本模式打开的文件时,请不要使用os.linesep作为行终止符(默认);)

use a single '\n' instead, on all platforms.

(在所有平台上都使用一个'\ n'代替。)

Some useful reading:

(一些有用的读物??:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...