只是想知道在 python 中我是否需要在我正在撰寫的字串中附加一個 '\n' 以便我撰寫的下一個字串與前一個字串不在同一行。示例代碼:
homeFilePath = "/home/myname/testFile.out"
fp = open(homeFilePath, 'w ')
fp.write("Line one")
fp.write("Line two")
fp.write("Line 3")
我正在尋找我的檔案以包含:
Line one
Line two
Line 3
我應該提到我正在使用 python 版本 2.7.5
uj5u.com熱心網友回復:
您可以直接使用print而不是使用fp.write。
from __future__ import print_function
homeFilePath = "/home/myname/testFile.out"
with open(homeFilePath, 'w ') as fp:
print("Line one", file=fp)
print("Line two", file=fp)
print("Line 3", file=fp)
(這比使用等價的print陳述句,print >>fp, "Line one"等要好得多)
uj5u.com熱心網友回復:
您可以使用以下內容:
fp.writelines(['line one','line two', 'line 3'])
或者您可以使用 \n 轉義字符。
uj5u.com熱心網友回復:
不,您確實需要添加換行符。你的代碼會給你輸出
Line oneLine twoLine 3
您可以撰寫自己的函式來為您附加它,例如:
def writeNewline(fpIn, strIn):
if (not fpIn.closed):
fpIn.write(strIn "\n")
然后你應該得到你想要的輸出writeNewline:
fp = open(homeFilePath, 'w ')
writeNewline(fp, "Line one")
writeNewline(fp, "Line two")
writeNewline(fp, "Line 3")
fp.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461228.html
標籤:Python python-2.7 文件 回车 写
上一篇:從串列中讀取.gz檔案并列印行
