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

yipeiwu_com6年前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设计】。

相关文章

Python3安装pip工具的详细步骤

Python3安装pip工具的详细步骤

前几天安装Python的时候没有装上pip工具,所以只能现在手动安装了。 首先,访问https://bootstrap.pypa.io/get-pip.py这个网址,然后Ctrl+S将g...

Python smallseg分词用法实例分析

本文实例讲述了Python smallseg分词用法。分享给大家供大家参考。具体分析如下: #encoding=utf-8 #import psyco #psyco.full()...

Jupyter notebook在mac:linux上的配置和远程访问的方法

upyter Notebook已经逐渐取代IDE成为了多平台上写简单Python脚本或应用的几家选择。 Jupyter Notebook可以通过pip/pip3安装: pip3 inst...

Python内建模块struct实例详解

本文研究的主要是Python内建模块struct的相关内容,具体如下。 Python中变量的类型只有列表、元祖、字典、集合等高级抽象类型,并没有像c中定义了位、字节、整型等底层初级类型。...

解决python 输出是省略号的问题

这个问题非常非常重要,搞了一晚上都没解决好,但是真的很简单很简单, 如果你也 是用的numpy array, 如果你也想得到输出矩阵的全部内容,而不是省略形式, [[ 0.10284...