代码一:
# -*- coding: utf-8 -*-
'''
python读取文件,将文件中的空白行去掉
'''
def delblankline(infile, outfile):
infopen = open(infile, 'r',encoding="utf-8")
outfopen = open(outfile, 'w',encoding="utf-8")
lines = infopen.readlines()
for line in lines:
if line.split():
outfopen.writelines(line)
else:
outfopen.writelines("")
infopen.close()
outfopen.close()
delblankline("jb51.txt", "o.txt")
代码二:
# -*- coding: utf-8 -*-
'''
python读取文件,将文件中的空白行去掉
'''
def delblankline(infile, outfile):
infopen = open(infile, 'r',encoding="utf-8")
outfopen = open(outfile, 'w',encoding="utf-8")
lines = infopen.readlines()
for line in lines:
line = line.strip()
if len(line)!=0:
outfopen.writelines(line)
outfopen.write('\n')
infopen.close()
outfopen.close()
delblankline("jb51.txt", "o2.txt")
代码三:
#coding:utf-8
import sys
def delete(filepath):
f=open(filepath,'a+')
fnew=open(filepath+'_new.txt','wb') #将结果存入新的文本中
for line in f.readlines(): #对每一行先删除空格,\n等无用的字符,再检查此行是否长度为0
data=line.strip()
if len(data)!=0:
fnew.write(data)
fnew.write('\n')
f.close()
fnew.close()
if __name__=='__main__':
if len(sys.argv)==1:
print u"必须输入文件路径,最好不要使用中文路径"
else:
delete(sys.argv[1])
原文链接:python去掉空白行的多种实现代码,转载请注明来源!