python输出数据到文件时遇到空行就删掉_使用python从配置单元查询输出中删除空行...

i am performing a hive query and storing the output in a tsv file in the local FS. I am running a for loop for the hive query and passing different parameters. If the hive query returns no output once in the for loop it prints an empty line in the tsv file. This causes NULL values to be pushed to my DB in the backend. Hence, after the for loop runs and the file is created - i have the below code to remove all the empty lines printed, but it doesn't work.

How do i remove the empty line from this file?

` 395.9 429.61 PT

`

code:

with open('file.tsv','r+w') as file:

for line in file:

if line.strip():

file.write(line)

thanks

解决方案

Usually you would open the input file and write the non-empty lines to a second file:

with open('file.tsv') as infile, open('filtered_file.tsv', 'w') as outfile:

for line in infile:

if line.strip():

outfile.write(line)

If you want to filter the file inplace you can use FileInput with the inplace option:

import fileinput

for line in fileinput.FileInput("infile", inplace=1):

if line.strip():

print line

however, this uses an intermediate file and may not work in low disk space situations.

To filter the file inplace without allocating any additional disk space you could try something like this:

with open('file.tsv', 'r+') as infile:

read_pos = write_pos = 0

line = infile.readline()

while line:

read_pos += len(line)

if line.strip():

infile.seek(write_pos)

infile.write(line)

write_pos += len(line)

infile.seek(read_pos)

line = infile.readline()

# update file size to the new, possibly reduced, size

infile.truncate(write_pos)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值