温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用python怎么实现循环读取txt文档

发布时间:2021-02-25 15:55:51 来源:亿速云 阅读:542 作者:戴恩恩 栏目:开发技术

本文章向大家介绍使用python怎么实现循环读取txt文档,主要包括使用python怎么实现循环读取txt文档的使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

python是什么意思

Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。

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文档的文章就介绍到这了,更多相关的内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI