最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

python去掉空白行的多种实现代码

来源:懂视网 责编:小采 时间:2020-11-27 14:21:36
文档

python去掉空白行的多种实现代码

python去掉空白行的多种实现代码:这篇文章主要介绍了python去掉空白行实现代码,需要的朋友可以参考下测试代码 php.txt1:www.gxlcms.com 2:www.gxlcms.com 3:www.gxlcms.com 4:www.gxlcms.com 5:www.gxlcms.com 6:www.gxlcms.com 7:www.gxlcms.co
推荐度:
导读python去掉空白行的多种实现代码:这篇文章主要介绍了python去掉空白行实现代码,需要的朋友可以参考下测试代码 php.txt1:www.gxlcms.com 2:www.gxlcms.com 3:www.gxlcms.com 4:www.gxlcms.com 5:www.gxlcms.com 6:www.gxlcms.com 7:www.gxlcms.co

这篇文章主要介绍了python去掉空白行实现代码,需要的朋友可以参考下

测试代码 php.txt

1:www.gxlcms.com
2:www.gxlcms.com
3:www.gxlcms.com
4:www.gxlcms.com
5:www.gxlcms.com
6:www.gxlcms.com

7:www.gxlcms.com
8:www.gxlcms.com
9:www.gxlcms.com
10:www.gxlcms.com

11:www.gxlcms.com
12:www.gxlcms.com
13:www.gxlcms.com


14:www.gxlcms.com
15:www.gxlcms.com

16:www.gxlcms.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("php.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('
')
 infopen.close()
 outfopen.close()

delblankline("php.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(): #对每一行先删除空格,
等无用的字符,再检查此行是否长度为0 
 data=line.strip() 
 if len(data)!=0: 
 fnew.write(data) 
 fnew.write('
') 
 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+" ")

3. .readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。

文档

python去掉空白行的多种实现代码

python去掉空白行的多种实现代码:这篇文章主要介绍了python去掉空白行实现代码,需要的朋友可以参考下测试代码 php.txt1:www.gxlcms.com 2:www.gxlcms.com 3:www.gxlcms.com 4:www.gxlcms.com 5:www.gxlcms.com 6:www.gxlcms.com 7:www.gxlcms.co
推荐度:
标签: 去掉 实现 代码
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top