当前第2页 返回上一页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # -*- 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( "php.txt" , "o2.txt" )
|
代码三:python2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #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去掉空白行的多种实现代码的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python如何实现杨辉三角形 (代码)
django中怎么更改默认数据库为mysql(详细过程)
Python会取代php吗?
如何用Python代码温度转换?
Python中关于list与numpy.ndarry切片两者的对比详解
Python怎么处理dataframe的时间字段
Python学习之图解变量与赋值
Python如何通过future处理并发问题的实例详解
Python中表示字符串的几种方法介绍
Python print用法详解
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python去掉空白行的多种实现代码