測(cè)試代碼 php.txt
1:www.gxlcms.com 2:www.gxlcms.com 3:www.gxlcms.com 4:www.gxlcms.com 5:www.gxlcms.com 6:www.gxlcms.com 7:www.gxlcms.com 8:www.gxlcms.com 9:www.gxlcms.com 10:www.gxlcms.com 11:www.gxlcms.com 12:www.gxlcms.com 13:www.gxlcms.com 14:www.gxlcms.com 15:www.gxlcms.com 16:www.gxlcms.com
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(' ') 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') #將結(jié)果存入新的文本中 for line in f.readlines(): #對(duì)每一行先刪除空格, 等無用的字符,再檢查此行是否長度為0 data=line.strip() if len(data)!=0: fnew.write(data) fnew.write(' ') f.close() fnew.close() if __name__=='__main__': if len(sys.argv)==1: print u"必須輸入文件路徑,最好不要使用中文路徑" else: delete(sys.argv[1])
代碼解析:
1. Python split()通過指定分隔符對(duì)字符串進(jìn)行切片,返回分割后的字符串列表。str.split()分隔符默認(rèn)為空格。
2. 函數(shù) writelines(list)
函數(shù)writelines可以將list寫入到文件中,但是不會(huì)在list每個(gè)元素后加換行符,所以如果想每行都有換行符的話需要自己再加上。
例如:for line in lines:
outfopen.writelines(line+" ")
3. .readlines() 自動(dòng)將文件內(nèi)容分析成一個(gè)行的列表,該列表可以由 Python 的 for ... in ... 結(jié)構(gòu)進(jìn)行處理。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com