這篇文章主要介紹了python去掉空白行實現程式碼,需要的朋友可以參考下
測試程式碼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程式碼
程式碼一
# -*- 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")
程式碼二
# -*- 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
#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去掉空白行的多種實作程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!