python去掉空白行的多種實現代碼,python去掉空白代碼

來源:互聯網
上載者:User

python去掉空白行的多種實現代碼,python去掉空白代碼

測試代碼 jb51.txt

1:www.jb51.net2:www.jb51.net3:www.jb51.net4:www.jb51.net5:www.jb51.net6:www.jb51.net7:www.jb51.net8:www.jb51.net9:www.jb51.net10:www.jb51.net11:www.jb51.net12:www.jb51.net13:www.jb51.net14:www.jb51.net15:www.jb51.net16:www.jb51.net

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("jb51.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("jb51.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 ... 結構進行處理。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.