[英]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.