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

相关文章

Python二进制文件读取并转换为浮点数详解

Python二进制文件读取并转换为浮点数详解

本文所用环境: Python 3.6.5 |Anaconda custom (64-bit)| 引言 由于某些原因,需要用python读取二进制文件,这里主要用到struct包,而这...

matlab中实现矩阵删除一行或一列的方法

实例如下所示: >> A=[1,2,3;4,5,6;7,8,9] A = 1 2 3 4 5 6 7 8 9 删除行: >> A...

Python基于opencv的图像压缩算法实例分析

本文实例讲述了Python基于opencv的图像压缩算法。分享给大家供大家参考,具体如下: 插值方法: CV_INTER_NN - 最近邻插值, CV_INTER_LINEAR - 双线...

初步解析Python下的多进程编程

要让Python程序实现多进程(multiprocessing),我们先了解操作系统的相关知识。 Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。普通的函数调用,...

Python 读取指定文件夹下的所有图像方法

Python 读取指定文件夹下的所有图像方法

(1)数据准备 数据集介绍: 数据集中存放的是1223幅图像,其中756个负样本(图像名称为0.1~0.756),458个正样本(图像名称为1.1~1.458),其中:"."前的标号为样...