[英]Python: How to write the output of python script to a file in the same line separated by tab
我是Python(2.7.15)的新手。 我試圖將我的Python腳本的輸出附加到由制表符分隔的文本文件中。
以下是我的代碼的一部分:
for key,value in d.iteritems():
with open('output.txt', 'a') as file:
file.write(key + "\t" + value + "\t")
.....
....
for item in data["response"]["docs"]:
titleValue = (item['title'])
with open('/tmp/output.txt', 'a') as file:
file.write(titleValue + "\n")
我的輸出文件如下所示:
FirstKey FirstValue
FirstTitle
SecondKey SecondValue
SecondTitle
基本上,我想在同一行中將這些值打印為制表符分隔值,並在新行中將下一行作為選項卡分隔值輸出,並以此類推,如下所示:
FirstKey FirstValue FirstTitle
SecondKey SecondValue SecondTitle
我怎樣才能做到這一點? file.write在新行中打印它。 我希望它在同一行中打印
首先應該注意, file.write()
不會隱式添加任何換行符,並且您獲得的那些換行符會以某種方式在提供給該函數的參數中傳遞。
不幸的是,從示例中尚不清楚如何獲得書面的鍵和值。 但是請注意,標題行(例如,帶有FirstTitle
)在標題本身之前包含一個縮進,可能是一個制表符。 由此,我假設d
詞典中的值是一些以換行符結尾的字符串。
這樣, key + "\\t" + value + "\\t"
(寫入文件)將產生類似於"FirstKey\\tFirstValue\\n\\t"
,它解釋了您得到的輸出。 為了獲得預期的結果,請確保這些值不包含結尾的換行符,例如,通過為它們調用str.rstrip :
value = value.rstrip()
使用%
, format
和join
比+
更具Pythonic性。
首先, join
運行更快,特別是在文本數量較大且代碼更清晰的情況下。 如下:
words = ["Thanks", "for", "contributing", "an", "answer", "to", "Stack", "Overflow!"]
text = "\t".join(words)
其次, format
可以根據需要設置文本格式。 如下:
text1 = "{}\t{}\t{}\t".format(1, 'A', 1.343) # output: 1 A 1.343
text2 = "%04d\t%5f" % (1, 3.1415926) # output: 0001 3.141593
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.