Python 从我保存在本地文件系统上的配置单元查询输出中删除空行

Python 从我保存在本地文件系统上的配置单元查询输出中删除空行,python,hadoop,hive,Python,Hadoop,Hive,我正在devbox上运行一个python脚本,在网格网关框上远程ssh,以启动另一个python脚本,该脚本运行配置单元查询并返回输出,然后以datestamp.tsv格式保存在devbox上 对于一些查询,我必须为两个集群运行for循环。问题是输出正在保存,但有空行,我希望日期戳位于查询输出之后。这是我现在的输出- 2014_03_28 PT 588.12 396.73 2014_03_28 DB 0.17 0.0 每次在for循环中运行查询后都会有一个空行 如何删除空行?

我正在devbox上运行一个python脚本,在网格网关框上远程ssh,以启动另一个python脚本,该脚本运行配置单元查询并返回输出,然后以datestamp.tsv格式保存在devbox上

对于一些查询,我必须为两个集群运行for循环。问题是输出正在保存,但有空行,我希望日期戳位于查询输出之后。这是我现在的输出-

2014_03_28 PT 588.12    396.73

2014_03_28 DB 0.17      0.0
每次在for循环中运行查询后都会有一个空行

如何删除空行?把邮戳放在最后。我希望它的输出格式为-

PT 588.12    396.73 2014_03_28
DB 0.17      0.0  2014_03_28
父脚本:

def get_compute_resources():
  global output
  ensure_directory(pipeline_name, user, star_date, "daily_compute_resources")
  for grid in grids:
    cmd = 'ssh -2 -i /home/abcd/.ssh/id_dsa -l abcd -o StrictHostKeyChecking=no -o CheckHostIP=no hostname "python2.6 /homes/abcd/starling/fetch_daily_user_summary.py -u ' + user + ' -g ' + grid + ' -d ' + starling_date + '" >> /home/abcd/projects/starling/daily_compute_resources/'+ pipeline_name +'/'+ user +'/'+ starling_date +'.tsv'
    resources = make_call(cmd).rstrip()
    print resources
远程计算机脚本:

cmd = "/home/y/bin/hive -e 'use star; SELECT ROUND(SUM((map_slot_seconds)/3600/24/2),2), ROUND(SUM((reduce_slots_seconds)/3600/24/2),2) from starling_job_summary where user=%s and grid=%s and dt like %s group by dt;' -hiveconf mapred.job.queue.name=unfunded -hiveconf mapred.reduce.tasks=1" % (user, grid, date)
  resources = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
  output = output_date+' '+output_grid+' '+resources
  print output

谢谢。

这应该行得通。它假定您在执行python的同一目录中拥有作为名为input.txt的文件提供的数据,并以output.txt文件所需的格式提供数据。
if line.strip()
检查只会忽略完全是空白的行,除此之外,这里唯一有点酷的是将日期与行的其余部分分隔开的maxplit参数to split()

infile = 'input.txt'
outfile = 'output.txt'

with open(infile) as f:
    with open(outfile, mode='w') as output:
        data = f.readlines()
        for line in data:
            if line.strip():
                date, rest = line.split(maxsplit=1)
                date = date.strip()
                rest = rest.strip()
                output.write(rest + ' ' + date + "\n")
也许可以在某种程度上清理空白处理,但这更简单

输出:

PT 588.12    396.73 2014_03_28
DB 0.17      0.0 2014_03_28

额外的空白可能分别来自
output\u date
resources
上的前导或尾随换行符。尝试一下:

print '{date} {grid} {res}'.format(date=output_date.strip(),
                                   grid=grid,
                                   res=resources.strip())

一般来说,使用
str.format
是使用变量数据创建字符串的常规方法。您可以使用
%
语法在子脚本中执行类似的操作,但您可以使用此方法提高父脚本的可读性。

我认为您必须更改
打印
语句,使它们以逗号结尾:

print output,
发件人:

“\n”字符写在末尾,除非print语句 以逗号结尾


你能把代码发到你真正记录信息的地方吗?@DarinDouglass-我用父脚本和远程脚本编辑了这个问题。这似乎增加了一个额外的步骤来处理和创建一个文件,我不想这样做。我刚刚编辑了我的问题,以反映我的剧本——@体面