2017-05-24 159 views
3

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

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

一个注意:你重新分配给'dir'命名空间'os.listdir(filedir)'。这意味着你正在写内建的'dir'函数,这是不推荐的。虽然它不会影响你的输出,但这是一种“风格”考虑。 – blacksite

+0

好点!稍后会尝试改进代码。 – user8061394

回答

2

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

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

你可以试试这个没有使用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() 

对于每个文件路径,代码打开文件,其内容读取一行行,然后写入了文件,最后将f的内容写入文件,除了f中的最后一个元素(空行)外。

+0

感谢您的意见。但由于某些原因,这些空行仍然存在...... – user8061394

0

我想这应该能正常运行

new_file.write(f[:-1]) 
1

您可以使用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) 

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

相关问题