概述
测试代码 jb51.txt
1:www.uoften.com 2:www.uoften.com 3:www.uoften.com 4:www.uoften.com 5:www.uoften.com 6:www.uoften.com 7:www.uoften.com 8:www.uoften.com 9:www.uoften.com 10:www.uoften.com 11:www.uoften.com 12:www.uoften.com 13:www.uoften.com 14:www.uoften.com 15:www.uoften.com 16:www.uoften.com
python代码
代码一
# -*- 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")
代码三:python2
#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])
效果图
代码解析:
1. Python split()通过指定分隔符对字符串进行切片,返回分割后的字符串列表。str.split()分隔符默认为空格。
2. 函数 writelines(list)
函数writelines可以将list写入到文件中,但是不会在list每个元素后加换行符,所以如果想每行都有换行符的话需要自己再加上。
例如:for line in lines:
outfopen.writelines(line+"\n")
3. .readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。
最后
以上就是干净店员为你收集整理的python去掉空白行的多种实现代码的全部内容,希望文章能够帮你解决python去掉空白行的多种实现代码所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复