python实现对文件进行切分行的方法

发布时间:2020-07-30 13:47:39 作者:小猪
来源:亿速云 阅读:240

这篇文章主要讲解了python实现对文件进行切分行的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

针对配置文件进行切分,重组,每隔30行为一段,进行重新生成功能。

代码如下

#!/usr/local/python/bin/python
# coding=utf-8
import sys
import re
import os
f = open('config.conf','r')
#判断文件条数
def file_num(filename):
  num_col = 0
  with open(filename,'rb') as Fnum:
    while(Fnum.readline() !=''):
     num_col = num_col + 1
  return num_col
  

file_num = file_num('config.conf')
print '文件总条数:' + str(file_num)

i = 0 #设置计数器
while i < file_num :       #表示文件行数
  with open('/tmp/newfile/newfile'+str(i),'w') as f1:
    for j in range(0,30) : #这里设置每个子文件的大小
      if i <= file_num : #这里判断是否已结束,否则最后可能报错
        f1.writelines(f.readline())
        i = i+1
      else:
        break

filepath2='/tmp/newfile/'
def eachFile(filepath):
  num = 1
  pathDir = sorted(os.listdir(filepath))
  for allDir in pathDir:
    child = os.path.join('%s%s' % (filepath, allDir))
    file_name = child.decode('gbk')
    print file_name
    with open('/tmp/check.py','a+') as f2:
     fopen = open(file_name, 'r+')
     f2.writelines("# config.py sql" + str(num) + " begin\n")
     count=0
     for line in fopen.readlines(): 
       if count == 0:
        f2.writelines(line)
        count= count+1
       else:
        f2.writelines("UNION ALL " + line)
     f2.writelines("# config.py sql" + str(num) + " end\n")
     f2.writelines("\n")
     num = num + 1

eachFile(filepath2)

脚本说明:

目录路径:/tmp

配置文件:config.conf

准备目录:/tmp/newfile/

最终新的配置文件为:check.py

看完上述内容,是不是对python实现对文件进行切分行的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. python实现对图片进行旋转,放缩,裁剪的功能
  2. 对Python实现累加函数的方法详解

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

python

上一篇:如何实现golang文件服务器

下一篇:更改pycharm显示字体的方法

相关阅读

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

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