python 循環(huán)讀取txt文檔 并轉(zhuǎn)換成csv的方法
更新時(shí)間:2018年10月26日 10:46:53 作者:liang890319
今天小編就為大家分享一篇python 循環(huán)讀取txt文檔 并轉(zhuǎn)換成csv的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
如下所示:
# -*- coding: utf-8 -*- """ Created on Fri Jul 29 15:49:06 2016 @author: user """ 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 # 打開一個(gè)文件 fo = open(fileOutList[files], "wb") fo.write( mainContent); # 關(guān)閉打開的文件 fo.close()
以上這篇python 循環(huán)讀取txt文檔 并轉(zhuǎn)換成csv的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python如何讀取和存儲(chǔ)dict()與.json格式文件
這篇文章主要介紹了python如何讀取和存儲(chǔ)dict()與.json格式文件,具有很好的參考價(jià)值,希望對大家有所幫助。2022-06-06使用Python的Flask框架實(shí)現(xiàn)視頻的流媒體傳輸
這篇文章主要介紹了使用Python的Flask框架實(shí)現(xiàn)視頻的流媒體傳輸,包括從攝像機(jī)獲取幀到web瀏覽器的數(shù)字流傳輸,需要的朋友可以參考下2015-03-03Python configparser模塊應(yīng)用過程解析
這篇文章主要介紹了Python configparser模塊應(yīng)用過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08Pandas索引排序 df.sort_index()的實(shí)現(xiàn)
本文主要介紹了Pandas索引排序 df.sort_index()的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Python3.2中Print函數(shù)用法實(shí)例詳解
這篇文章主要介紹了Python3.2中Print函數(shù)用法,以實(shí)例形式較為詳細(xì)的分析了Python3.2中Print函數(shù)輸出的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-05-05