您好,登錄后才能下訂單哦!
本文章向大家介紹使用python怎么實(shí)現(xiàn)循環(huán)讀取txt文檔,主要包括使用python怎么實(shí)現(xiàn)循環(huán)讀取txt文檔的使用實(shí)例、應(yīng)用技巧、基本知識點(diǎn)總結(jié)和需要注意事項(xiàng),具有一定的參考價值,需要的朋友可以參考一下。
Python是一種跨平臺的、具有解釋性、編譯性、互動性和面向?qū)ο蟮哪_本語言,其最初的設(shè)計是用于編寫自動化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發(fā)獨(dú)立的項(xiàng)目和大型項(xiàng)目。
import os #從文件中讀取某一行 linecache.checkcache可以刷新cache ,linecache可以緩存某一行的信息 import linecache def GetFileNameAndExt(filename): (filepath,tempfilename) = os.path.split(filename); (shotname,extension) = os.path.splitext(tempfilename); return shotname fileList=[] fileOutList=[] for filename in os.listdir(r'D:\input'): pa='D:\input\%s'%filename fileList.append(pa) name=GetFileNameAndExt(pa) name+='.csv' pa='D:\output\%s'%name fileOutList.append(pa) for files in range(0,len(fileList)): lineCount = len(open(fileList[files],'rU').readlines()) print '====this file %s : %d lines'%(fileList[files],lineCount) print '====有效數(shù)據(jù)行數(shù) %d lines'%( lineCount-14) global cnt global mainContent global s1 s1='' mainContent='' cnt=0 for var in range(14,lineCount+1): theline = linecache.getline(fileList[files], var) s= theline[15:13+104] s = s.replace(' ',',') # 將字符串里的k全部替換為8 s = s.replace(' ',',') # 將字符串里的k全部替換為8 if var%2 == 0: s+=(',') s1= s else: string =s1.strip('\n') + s+'\n' mainContent +=string cnt+=1 print '====out line count =%d'%cnt # print s print '===final data=====' # print mainContent # 打開一個文件 fo = open(fileOutList[files], "wb") fo.write( mainContent); # 關(guān)閉打開的文件 fo.close()
到此這篇關(guān)于使用python怎么實(shí)現(xiàn)循環(huán)讀取txt文檔的文章就介紹到這了,更多相關(guān)的內(nèi)容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。