如何使用追加,自定义分隔符和在Python 2中抑制尾部空格?
问题描述:
我打印在该命令文件我的输出:如何使用追加,自定义分隔符和在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://*.com/questions/22116482/python-syntax-help-sep-t) – smci