python 把文件内容分成三列
关注:197 答案:2 mip版
解决时间 2021-01-20 01:51
提问者葃日懙妳
2021-01-19 05:40
比如有一文件 cat file.txt:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
我想分成三列显示: cat file.txt
1 6 11
2 7 12
3 8 13
4 9 14
5 10
#!/usr/bin/env python
def itercolumn(lines, column_line):
block = []
for ln in lines:
block.append(ln)
if len(block) == column_line:
yield block
block = []
if 0 < len(block) < column_line:
block = block + [''] * (column_line - len(block))
yield block
lns = [ln.strip() for ln in open("file.txt", 'r')]
column_num = 3
column_ln = (column_num + len(lns) - 1) / column_num
columns = [column for column in itercolumn(lns, column_ln)]
for row in zip(*columns):
print "\t".join(row)
求更简洁更高效的 PYTHON代码, 上面代码有点复杂
最佳答案
二级知识专家風聲提筆
2021-01-19 05:50
#!/usr/bin/env python
with open('file.txt') as f:
d=f.readlines()
with open('file.txt','w') as f:
for i in range(len(d)):
if (i+1)%3!=0:
f.write('%s ' %d[i].strip())
else:
f.write(d[i])
全部回答
1楼亲亲兔耳朵
2021-01-19 06:09
#!/usr/bin/env python with open('file.txt') as f: d=f.readlines() with open('file.txt','w') as f: for i in range(len(d)): if (i+1)%3!=0: f.write('%s ' %d[i].strip()) else: f.write(d[i])
我要举报
如果感觉以上信息为低俗/不良/侵权的信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!
点此我要举报以上信息!
推荐资讯
大家都在看