Home  >  Article  >  Backend Development  >  Various implementation codes for removing blank lines in Python

Various implementation codes for removing blank lines in Python

不言
不言Original
2018-07-11 10:38:595265browse

This article mainly introduces the code for removing blank lines in python. Friends who need it can refer to

Test code php.txt

1:www.php.cn
2:www.php.cn
3:www.php.cn
4:www.php.cn
5:www.php.cn
6:www.php.cn

7:www.php.cn
8:www.php.cn
9:www.php.cn
10:www.php.cn

11:www.php.cn
12:www.php.cn
13:www.php.cn


14:www.php.cn
15:www.php.cn

16:www.php.cn

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn