python 循环读取txt文档 并转换成csv的方法

yipeiwu_com5年前Python基础

如下所示:

# -*- 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()

以上这篇python 循环读取txt文档 并转换成csv的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python正则表达式及使用正则表达式的例子

正则表达式 正则表达用来匹配字符串 正则表达式匹配过程 依次拿出表达式和文本中的字符串进行比价 如果每个字符都能匹配,则匹配成功;一旦有匹配不成功的字符,则匹配失败 如果有...

Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例

Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例

本文实例讲述了Python2.7基于笛卡尔积算法实现N个数组的排列组合运算。分享给大家供大家参考,具体如下: 说明:本人前段时间遇到的求n个数组的所有排列组合的问题,发现笛卡尔积算法可以...

python中property属性的介绍及其应用详解

Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回。 使用property修饰的实例方法被调用时,可以把它当做实例属性一样 pr...

Python实现的根据IP地址计算子网掩码位数功能示例

Python实现的根据IP地址计算子网掩码位数功能示例

本文实例讲述了Python实现的根据IP地址计算子网掩码位数功能。分享给大家供大家参考,具体如下: #!/usr/bin/env python # coding:utf-8 #!/b...

Python实现图片拼接的代码

具体代码如下所示: import os from PIL import Image UNIT_SIZE = 220 # the size of image save_path = '...