python去掉空白行的两种代码
测试代码 jb51.txt 1:www.jb51.net 2:www.jb51.net 3:www.jb51.net 4:www.jb51.net 5:www.jb51.net 6:www.jb51.net 7:www.jb51.net 8:www.jb51.net 9:www.jb51.net 10:www.jb51.net 11:www.jb51.net 12:www.jb51.net 13:www.jb51.net 14:www.jb51.net 15:www.jb51.net 16:www.jb51.net
方法一:
# -*- 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")
作者:龙飞
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!