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

yipeiwu_com5年前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

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基础入门详解(文件输入/输出 内建类型 字典操作使用方法)

一、变量和表达式 复制代码 代码如下:>>> 1 + 1         &n...

pytorch 加载(.pth)格式的模型实例

pytorch 加载(.pth)格式的模型实例

有一些非常流行的网络如 resnet、squeezenet、densenet等在pytorch里面都有,包括网络结构和训练好的模型。 pytorch自带模型网址:https://pyto...

Python实现读取txt文件并转换为excel的方法示例

本文实例讲述了Python实现读取txt文件并转换为excel的方法。分享给大家供大家参考,具体如下: 这里的txt文件内容格式为: 892天平天国定都在?A开封B南京C北京(B)...

用python做一个搜索引擎(Pylucene)的实例代码

用python做一个搜索引擎(Pylucene)的实例代码

1.什么是搜索引擎? 搜索引擎是“对网络信息资源进行搜集整理并提供信息查询服务的系统,包括信息搜集、信息整理和用户查询三部分”。如图1是搜索引擎的一般结构,信息搜集模块从网络采集信息到网...

pytorch实现mnist分类的示例讲解

torchvision包 包含了目前流行的数据集,模型结构和常用的图片转换工具。 torchvision.datasets中包含了以下数据集 MNIST COCO(用于图像标注和目标检测...