首页 > 编程 > Python > 正文

python分割文件的常用方法

2020-02-23 06:08:19
字体:
来源:转载
供稿:网友

本文大家整理了一些比较好用的关于python分割文件的方法,方法非常的简单实用。分享给大家供大家参考。具体如下:

例子1 指定分割文件大小

配置文件 config.ini:
代码如下:[global]
#原文件存放目录
dir1=F:/work/python/3595/pyserver/test
#新文件存放目录
dir2=F:/work/python/3595/pyserver/test1

python 代码如下:

代码如下:#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys,ConfigParser
class file_openate(object):
def __init__(self):
    #初如化读取数据库配置
    dir_config = ConfigParser.ConfigParser()
    file_config=open('config.ini',"rb")
    dir_config.readfp(file_config)
    self.dir1=str(dir_config.get("global","dir1"))
    self.dir1=unicode(self.dir1,'utf8')
    self.dir2=str(dir_config.get("global","dir2"))
    self.dir2=unicode(self.dir2,'utf8')
    file_config.close()
#print self.dir2
#self.dir1="F://work//python//3595//pyserver//test"
def file_list(self):
    input_name_han="软件有不确认性,前期使用最好先备份,以免发生数据丢失,确认备份后,请输入要分割的字节大小,按b来计算".decode('utf-8')
    print input_name_han
    while 1:
input_name=raw_input("number:")
if input_name.isdigit():
    input_name=int(input_name)
    os.chdir(self.dir1)
    for filename in os.listdir(self.dir1):
os.chdir(self.dir1)
#print filename
name, ext = os.path.splitext(filename)
file_size=int(os.path.getsize(filename))
f=open(filename,'r')
chu_nmuber=0
while file_size >= 1:
    #print file_size
    chu_nmuber=chu_nmuber + 1
    if file_size >= input_name:
file_size=file_size - input_name
a=f.read(input_name)
os.chdir(self.dir2)
filename1=name + '-' + str(chu_nmuber) + ext
new_f=open(filename1,'a')
new_f.write(a)
new_f.close()
#print file_size
    else:
a=f.read()
os.chdir(self.dir2)
filename1=name + '-' + str(chu_nmuber) + ext
new_f=open(filename1,'a')
new_f.write(a)
new_f.close()
break
print "分割成功".decode('utf-8') + filename
f.close()
else:
    print "请输入正确的数字,请重新输入".decode('utf-8')
file_name=file_openate()
file_name.file_list()

例子2,按行分割文件大小

代码如下:#!/usr/bin/env python
#--*-- coding:utf-8 --*--
import os
class SplitFiles():
    """按行分割文件"""
    def __init__(self, file_name, line_count=200):

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表