哪有什么岁月静好,不过是有人替你负重前行!

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")
posted @ 2021-10-16 20:49  longfei825  阅读(760)  评论(0编辑  收藏  举报