[英]Remove the last empty line from each text file
我有很多文本文件,每个文本文件末尾都有一个空行。 我的脚本似乎没有删除它们。 有人可以帮忙吗?
# 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()
你可以使用以下方法删除最后一个空行:
with open(filepath, 'r') as f:
data = f.read()
with open(output, 'w') as w:
w.write(data[:-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)
这将删除文件末尾的所有空行。 如果没有空行,它将不会更改文件。
您可以在不使用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中的最后一个元素除外,即空行。
我认为这应该工作正常
new_file.write(f[:-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.