This article mainly introduces Python to remove the blank line implementation code, the need for friends can refer to the following
Test Code Php.txt
1:www.php.cn2:www.php.cn3:www.php.cn4:www.php.cn5:www.php.cn6:www.php.cn7:www.php.cn8:www.php.cn9:www.php.cn10 : www.php.cn11:www.php.cn12:www.php.cn13:www.php.cn14:www.php.cn15:www.php.cn16:www.php.cn
Python code
Code One
#-*-Coding:utf-8-*-"Python reads the file, removes the blank line from the file ' 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 two
#-*-Coding:utf-8-*-"Python reads the file, removes the blank line from the file ' 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.st RIP () if Len (line)!=0: outfopen.writelines (line) outfopen.write (' \ n ') infopen.close () Outfopen.close ( ) Delblankline ("Php.txt", "O2.txt")
Code Three: 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 Wait for useless characters, and then check if this row is 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 "must enter file path, preferably do not use Chinese path" Else: Delete (sys.argv[1])
Code parsing:
1. Python split () slices the string by specifying a delimiter, returning the segmented list of strings. The Str.split () delimiter defaults to a space.
2. function Writelines (list)
The function Writelines can write a list to a file, but does not add a newline character after each element of the list, so you need to add it yourself if you want to have a newline character for each line.
For example: For line in lines:
Outfopen.writelines (line+ "\ n")
3.. readlines () automatically parses the contents of the file into a list of rows that can be used by Python for ... in ... Structure for processing.