python删除文件中的空行_Python - 删除文件末尾的空行文本

我正在编写修改任何文本文件的脚本。它用空行代替空白行。它会擦除文件末尾的空白行。该图像显示我想要的输出。Python - 删除文件末尾的空行文本

9egTX.png

我能够得到非常接近所需的输出。问题是我无法摆脱最后一个空白行。我认为这与最后一行有关。例如' the lines below me should be gone实际上看起来像这样' the lines below me should be gone\n'它看起来像在上一行创建了新行。 e.g如果4号线有\n比5号线实际上将是空行不行4.

我要指出,我不能使用rstrip或strip

到目前为止我的代码。

def clean_file(filename):

# function to check if the line can be deleted

def is_all_whitespace(line):

for char in line:

if char != ' ' and char != '\n':

return False

return True

# generates the new lines

with open(filename, 'r') as file:

file_out = []

for line in file:

if is_all_whitespace(line):

line = '\n'

file_out.append(line)

# removes whitespaces at the end of file

while file_out[-1] == '\n': # while the last item in lst is blank

file_out.pop(-1) # removes last element

# writes the new the output to file

with open(filename, 'w') as file:

file.write(''.join(file_out))

clean_file('test.txt')

2014-01-30

Vader

+3

你已经做了很多关于这个问题的研究,这很清楚。 +1。 –

+1

为什么“不能”使用'.rstrip()'? –

+0

@KarlKnechtel那会太容易 –

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值