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
217 views
in Technique[技术] by (71.8m points)

python - 在编写文件时,如何在Python上指定换行符?(How do I specify new lines on Python, when writing on files?)

In comparison to Java (in a string), you would do something like "First Line\r\nSecond Line" .

(与Java(以字符串形式)相比,您将执行类似于"First Line\r\nSecond Line" 。)

So how would you do that in Python, for purposes of writing multiple lines to a regular file?

(那么,为了在常规文件中写多行,您将如何在Python中执行此操作?)

  ask by FabianCook translate from so

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

1 Reply

0 votes
by (71.8m points)

It depends on how correct you want to be.

(这取决于您想做的正确程度。)

\n will usually do the job.

(\n通常可以胜任。)

If you really want to get it right, you look up the newline character in the os package .

(如果您确实想解决问题,请在os包中查找换行符。)

(It's actually called linesep .)

((实际上称为linesep 。))

Note: when writing to files using the Python API, do not use the os.linesep .

(注意:使用Python API写入文件时,请勿使用os.linesep 。)

Just use \n ;

(只需使用\n ;)

Python automatically translates that to the proper newline character for your platform.

(Python会自动将其转换为适合您平台的换行符。)


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

...