从每个文本文件中删除最后一个空行

use*_*394 5 python

我有很多文本文件,每个文件最后都有一个空行。我的脚本似乎没有删除它们。有人可以帮忙吗?

# python 2.7
import os
import sys
import re

filedir = 'F:/WF/'
dir = os.listdir(filedir)

for filename in dir:
    if 'ABC' in filename: 
        filepath = os.path.join(filedir,filename)
        all_file = open(filepath,'r')
        lines = all_file.readlines()
        output = 'F:/WF/new/' + filename

        # Read in each row and parse out components
        for line in lines:
            # Weed out blank lines
            line = filter(lambda x: not x.isspace(), lines)

            # Write to the new directory 
            f = open(output,'w')
            f.writelines(line)
            f.close() 
Run Code Online (Sandbox Code Playgroud)

Mar*_*ans 6

您可以使用 Python 的rstrip()函数来执行此操作,如下所示:

filename = "test.txt"

with open(filename) as f_input:
    data = f_input.read().rstrip('\n')

with open(filename, 'w') as f_output:    
    f_output.write(data)
Run Code Online (Sandbox Code Playgroud)

这将从文件末尾删除所有空行。如果没有空行,它不会更改文件。


Moh*_*ohd 3

您可以使用以下方法删除最后一个空行:

with open(filepath, 'r') as f:
    data = f.read()
    with open(output, 'w') as w:
        w.write(data[:-1])
Run Code Online (Sandbox Code Playgroud)