# -*- 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 '====有效数据行数 %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); # 关闭打开的文件 fo.close()