This article mainly introduces the code for removing blank lines in python. Friends who need it can refer to
Test code php.txt
1:m.sbmmt.com 2:m.sbmmt.com 3:m.sbmmt.com 4:m.sbmmt.com 5:m.sbmmt.com 6:m.sbmmt.com 7:m.sbmmt.com 8:m.sbmmt.com 9:m.sbmmt.com 10:m.sbmmt.com 11:m.sbmmt.com 12:m.sbmmt.com 13:m.sbmmt.com 14:m.sbmmt.com 15:m.sbmmt.com 16:m.sbmmt.com
python code
Code 1
# -*- 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")
Code 2
# -*- 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")
Code 3: 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])
Code analysis:
1. Python split() splits the string by specifying the delimiter Slice, return the split string list. The str.split() delimiter defaults to spaces.
2. Function writelines(list)
The function writelines can write the list to the file, but it will not add a newline character after each element of the list, so if you want to have If you want to add a newline character, you need to add it yourself.
For example: for line in lines:
outfopen.writelines(line "\n")
3. .readlines() automatically analyzes the file content into a line A list that can be processed by Python's for ... in ... structure.
Related recommendations:
Python method to remove spaces from strings
The above is the detailed content of Various implementation codes for removing blank lines in Python. For more information, please follow other related articles on the PHP Chinese website!