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")
上一篇:JAVA环境变量一键配置工具


下一篇:微信小程序实现传参数的几种方法示例