如何使用追加,自定义分隔符和在Python 2中抑制尾部空格?

问题描述:

我打印在该命令文件我的输出:如何使用追加,自定义分隔符和在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://*.com/questions/22116482/python-syntax-help-sep-t) – smci

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.

您可以使用文件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

的空间来自于print使用逗号(Python的2.7?)。

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

应该解决这个问题。

+0

作品完美,谢谢 – Pol