每4个选项卡编写一个新的行文本文件python

2024-10-01 05:07:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有下面的数据,用制表符分开打印

print str(z).translate(None,"([]){},\"'").replace(' ','\t')

0.016611783537845426    0.5728972505882961  0.1723653381777387   0.44730982873820446    10  11  10  0.016611783537845426     0.5728972505882961 0.2526385373738682  0.03281263933004819 10  12  10  0.016611783537845426    0.5728972505882961  0.509414248773428

我怎么能写一个新的txt文件,但开始新行每说4个标签。所以得到4列。在

已经尝试了\n but im rubbsih的许多变体。在

例如:

^{pr2}$

为每个字符返回换行符。在


Tags: 文件数据txtnone标签变体replace制表符
2条回答

您可以使用^{} documentation中的grouper配方:

import itertools as it
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x')  > ABC DEF Gxx"
    args = [iter(iterable)] * n
    return it.izip_longest(fillvalue=fillvalue, *args)

然后您可以将输出生成为:

^{pr2}$

或者,如果要将其写入文件,请使用f.writelines

f.writelines('\t'.join(x for x in g if x) + '\n' for g in grouper(4, values))

这应该是有效的:

text = str(z).translate(None,"([]){},\"'").replace(' ','\t')

# convert to list
x = text.split()
# group by four items
x = [x[0::4],x[1::4],x[2::4],x[3::4]]
# convert back to text lines
print "\n".join(" ".join(i) for i in [x[0::4],x[1::4],x[2::4],x[3::4]])

相关问题 更多 >