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 threading的使用方法解析

Python threading的使用方法解析

一、 例子:我们对传参是有要求的必须传入一个元组,否则报错 import _thread as thread import time def loop1(in1): print(...

Django 跨域请求处理的示例代码

Django 跨域请求处理的示例代码

django处理Ajax跨域访问 使用javascript进行ajax访问的时候,出现如下错误 出错原因:javascript处于安全考虑,不允许跨域访问。下图是对跨域访问的解释:...

用python写的一个wordpress的采集程序

用python写的一个wordpress的采集程序

在学习python的过程中,经过不断的尝试及努力,终于完成了第一个像样的python程序,虽然还有很多需要优化的地方,但是目前基本上实现了我所要求的功能,先贴一下程序代码: 具体代码如...

使用Python进行目录的对比方法

如果进行单个文件的比较,可以使用difflib模块。虽然filecmp模块也能够进行单个文件的对比,但是前者能够提供观感更好的报告。如果我们只是想看一下两个目录中的某个文件是否一致而不关...

Python数据分析matplotlib设置多个子图的间距方法

注意,要看懂这里,必须具备简单的Python数据分析知识,必须知道matplotlib的简单使用! 例1: plt.subplot(221) # 第一行的左图 plt.subplo...