2016-11-24 31 views
-3

我打印在該命令文件我的輸出:如何使用追加,自定義分隔符和在Python 2中抑制尾部空格?

print >> outfile, columns2[0],"\t",columns2[1],"\t",columns2[2] 

我的問題是,我有一個「空間」在每列的內容結束。

我知道有些時候它可以解決與sep

print('foo', 'bar', sep='') 

但我不知道如何實現sep而在一個文件,我上面的命令寫:

print >> outfile 
+1

你爲什麼不寫''寫入文件? – 2016-11-24 13:57:15

+0

我想他是在談論在每個逗號插入的空間,而不是NL。 – totoro

+0

你在問Python 3或2嗎?如果Python 3,這可能是封閉的重複[python syntax help sep =「」,'\ t'](http://stackoverflow.com/questions/22116482/python-syntax-help-sep-t) – smci

回答

0

print()功能可以用來打印到任何文件,而不僅僅是sys.stdout。嘗試:

from __future__ import print_function 

print(*columns2, sep="\t", file=outfile) 

從文檔上print()

print(*objects, sep=' ', end='\n', file=sys.stdout)

The file argument must be an object with a write(string) method; if it is not present or None , sys.stdout will be used.

0

您可以使用文件write方法,使用write方法將不會在年底額外的換行符。推薦使用字符串連接方法在+運營商以及

outfile.write('\t'.join(column2)) 
# add + '\n' if need the new line 
# use column2[:2] if you have more items in list and only need slice of them 
+0

你的連接命令是非常有趣的,但我得到以下錯誤:「名稱」連接'未定義「 – Pol

+0

不應該有錯誤,我已經測試工作,確保你有'\ t'.join',在加入之前仔細檢查''\ t'.' – Skycc

+0

你是對的我寫了一個「,」而不是「。」。 – Pol

2

的空間來自於print使用逗號(Python的2.7?)。

print >> outfile, '\t'.join(columns2) 

應該解決這個問題。

+0

作品完美,謝謝 – Pol

相關問題