从屏幕上删除最后打印的字符

时间:2018-12-29 23:54:40

标签: python python-3.x

我有一段代码对文件进行排序,然后在屏幕上打印格式化的输出

.add

当我运行它时,给我这样的东西:

p1 = subprocess.Popen(('sort', '-nr',tempfile), stdout=subprocess.PIPE)
p2 = subprocess.Popen (('awk', '{print \""$2"\\":\" $1\"},\"} ' ),stdin=p1.stdout)

但是我只需要:

/tmp/whois.conf":382},
/tmp/yum.conf":970},
/tmp/hi/bhutpret":0}, 

它也为最后一行打印逗号“,”。如何通过程序从控制台删除此已打印的逗号?

1 个答案:

答案 0 :(得分:1)

请不要在最后一行打印逗号。

import subprocess
tempfile='input.txt'
p1 = subprocess.Popen(('sort', '-nr',tempfile), stdout=subprocess.PIPE)
p2 = subprocess.Popen (('awk', r'NR > 1 { printf(",\n") } { printf("%s\":%s}", $2, $1) } END{print ""}'),stdin=p1.stdout)

输出:

is":Pizza},
the":Keep},
really":I},
someone":Did}

我的文件“ input.txt”

I really love christmas
Keep the change ya filthy animal
Pizza is my fav food
Did someone say peanut butter?