简体   繁体   English

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

[英]Remove the last empty line from each text file

I have many text files, and each of them has a empty line at the end. 我有很多文本文件,每个文本文件末尾都有一个空行。 My scripts did not seem to remove them. 我的脚本似乎没有删除它们。 Can anyone help please? 有人可以帮忙吗?

# 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() 

you can remove last empty line by using: 你可以使用以下方法删除最后一个空行:

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

You can use Python's rstrip() function to do this as follows: 您可以使用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)

This will remove all empty lines from the end of the file. 这将删除文件末尾的所有空行。 It will not change the file if there are no empty lines. 如果没有空行,它将不会更改文件。

You can try this without using the re module: 您可以在不使用re模块的情况下尝试此操作:

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

for filename in dir:
    if 'ABC' in filename: 
        filepath = os.path.join(filedir,filename)

        f = open(filepath).readlines()
        new_file = open(filepath, 'w')
        new_file.write('')
        for i in f[:-1]:

           new_file.write(i)

       new_file.close()

For each filepath, the code opens the file, reads in its contents line by line, then writes over the file, and lastly writes the contents of f to the file, except for the last element in f, which is the empty line. 对于每个文件路径,代码打开文件,逐行读取其内容,然后写入文件,最后将f的内容写入文件,f中的最后一个元素除外,即空行。

我认为这应该工作正常

new_file.write(f[:-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM