python去掉空⽩⾏的多种实现代码测试代码
1:www.jb51
2:www.jb51
3:www.jb51
4:www.jb51
5:www.jb51
6:www.jb51
7:www.jb51
8:www.jb51
9:www.jb51
10:www.jb51
11:www.jb51
12:www.jb51
13:www.jb51
14:www.jb51
15:www.jb51
16:www.jb51writelines使用方法python
python代码
代码⼀
# -*- coding: utf-8 -*-
'''
python读取⽂件,将⽂件中的空⽩⾏去掉
'''
def delblankline(infile, outfile):
infopen = open(infile, 'r',encoding="utf-8")
outfopen = open(outfile, 'w',encoding="utf-8")
lines = adlines()
for line in lines:
if line.split():
outfopen.writelines(line)
else:
outfopen.writelines("")
infopen.close()
outfopen.close()
delblankline("", "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 = adlines()
for line in lines:
line = line.strip()
if len(line)!=0:
outfopen.writelines(line)
outfopen.write('\n')
infopen.close()
outfopen.close()
delblankline("", "o2.txt")
代码三:python2
#coding:utf-8
import sys
def delete(filepath):
f=open(filepath,'a+')
fnew=open(filepath+'_','wb')  #将结果存⼊新的⽂本中
for line adlines():        #对每⼀⾏先删除空格,\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 ... 结构进⾏处理。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。