我打印在該命令文件我的輸出:如何使用追加,自定義分隔符和在Python 2中抑制尾部空格?
print >> outfile, columns2[0],"\t",columns2[1],"\t",columns2[2]
我的問題是,我有一個「空間」在每列的內容結束。
我知道有些時候它可以解決與sep
:
print('foo', 'bar', sep='')
但我不知道如何實現sep
而在一個文件,我上面的命令寫:
print >> outfile
我打印在該命令文件我的輸出:如何使用追加,自定義分隔符和在Python 2中抑制尾部空格?
print >> outfile, columns2[0],"\t",columns2[1],"\t",columns2[2]
我的問題是,我有一個「空間」在每列的內容結束。
我知道有些時候它可以解決與sep
:
print('foo', 'bar', sep='')
但我不知道如何實現sep
而在一個文件,我上面的命令寫:
print >> outfile
的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 awrite(string)
method; if it is not present orNone
, sys.stdout will be used.
您可以使用文件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
你爲什麼不寫''寫入文件? – 2016-11-24 13:57:15
我想他是在談論在每個逗號插入的空間,而不是NL。 – totoro
你在問Python 3或2嗎?如果Python 3,這可能是封閉的重複[python syntax help sep =「」,'\ t'](http://stackoverflow.com/questions/22116482/python-syntax-help-sep-t) – smci