python分割文件的常用方法

本文大家整理了一些比较好用的关于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):
        """初始化要分割的源文件名和分割后的文件行数"""
        self.file_name = file_name
        self.line_count = line_count
    def split_file(self):
        if self.file_name and os.path.exists(self.file_name):
            try:
                with open(self.file_name) as f : # 使用with读文件
                    temp_count = 0
                    temp_content = []
                    part_num = 1
                    for line in f:
                        if temp_count < self.line_count:
                            temp_count += 1
                        else :
                            self.write_file(part_num, temp_content)
                            part_num += 1
                            temp_count = 1
                            temp_content = []
                        temp_content.append(line)
                    else : # 正常结束循环后将剩余的内容写入新文件中
                        self.write_file(part_num, temp_content)
            except IOError as err:
                print(err)
        else:
            print("%s is not a validate file" % self.file_name)
    def get_part_file_name(self, part_num):
        """"获取分割后的文件名称:在源文件相同目录下建立临时文件夹temp_part_file,然后将分割后的文件放到该路径下"""
        temp_path = os.path.dirname(self.file_name) # 获取文件的路径(不含文件名)
        part_file_name = temp_path + "temp_part_file"
        if not os.path.exists(temp_path) : # 如果临时目录不存在则创建
            os.makedirs(temp_path)
        part_file_name += os.sep + "temp_file_" + str(part_num) + ".part"
        return part_file_name
    def write_file(self, part_num, *line_content):
        """将按行分割后的内容写入相应的分割文件中"""
        part_file_name = self.get_part_file_name(part_num)
        print(line_content)
        try :
            with open(part_file_name, "w") as part_file:
                part_file.writelines(line_content[0])
        except IOError as err:
            print(err)
if __name__ == "__main__":
    sf = SplitFiles(r"F:\multiple_thread_read_file.txt")
    sf.split_file()

上面只是进行了分割了,如果我们又要合并怎么办呢?下面这个例子可以实现分割与合并哦,大家一起看看。

例子3, 分割文件与合并函数

代码如下:

#!/usr/bin/python
##########################################################################
# split a file into a set of parts; join.py puts them back together;
# this is a customizable version of the standard unix split command-line
# utility; because it is written in Python, it also works on Windows and
# can be easily modified; because it exports a function, its logic can
# also be imported and reused in other applications;
##########################################################################
     
import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes)   # default: roughly a floppy
     
def split(fromfile, todir, chunksize=chunksize):
    if not os.path.exists(todir):  # caller handles errors
os.mkdir(todir)    # make dir, read/write parts
    else:
for fname in os.listdir(todir):    # delete any existing files
    os.remove(os.path.join(todir, fname))
    partnum = 0
    input = open(fromfile, 'rb')   # use binary mode on Windows
    while 1:       # eof=empty string from read
chunk = input.read(chunksize)      # get next part <= chunksize
if not chunk: break
partnum  = partnum+1
filename = os.path.join(todir, ('part%04d' % partnum))
fileobj  = open(filename, 'wb')
fileobj.write(chunk)
fileobj.close()    # or simply open().write()
    input.close()
    assert partnum <= 9999 # join sort fails if 5 digits
    return partnum
    
if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == '-help':
print 'Use: split.py [file-to-split target-dir [chunksize]]'
    else:
if len(sys.argv) < 3:
    interactive = 1
    fromfile = raw_input('File to be split? ')       # input if clicked
    todir    = raw_input('Directory to store part files? ')
else:
    interactive = 0
    fromfile, todir = sys.argv[1:3]  # args in cmdline
    if len(sys.argv) == 4: chunksize = int(sys.argv[3])
absfrom, absto = map(os.path.abspath, [fromfile, todir])
print 'Splitting', absfrom, 'to', absto, 'by', chunksize
     
try:
    parts = split(fromfile, todir, chunksize)
except:
    print 'Error during split:'
    print sys.exc_info()[0], sys.exc_info()[1]
else:
    print 'Split finished:', parts, 'parts are in', absto
if interactive: raw_input('Press Enter key') # pause if clicked

join_file.py

代码如下:

#!/usr/bin/python
##########################################################################
# join all part files in a dir created by split.py, to recreate file. 
# This is roughly like a 'cat fromdir/* > tofile' command on unix, but is
# more portable and configurable, and exports the join operation as a
# reusable function.  Relies on sort order of file names: must be same
# length.  Could extend split/join to popup Tkinter file selectors.
##########################################################################
     
import os, sys
readsize = 1024
     
def join(fromdir, tofile):
    output = open(tofile, 'wb')
    parts  = os.listdir(fromdir)
    parts.sort()
    for filename in parts:
filepath = os.path.join(fromdir, filename)
fileobj  = open(filepath, 'rb')
while 1:
    filebytes = fileobj.read(readsize)
    if not filebytes: break
    output.write(filebytes)
fileobj.close()
    output.close()
     
if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == '-help':
print 'Use: join.py [from-dir-name to-file-name]'
    else:
if len(sys.argv) != 3:
    interactive = 1
    fromdir = raw_input('Directory containing part files? ')
    tofile  = raw_input('Name of file to be recreated? ')
else:
    interactive = 0
    fromdir, tofile = sys.argv[1:]
absfrom, absto = map(os.path.abspath, [fromdir, tofile])
print 'Joining', absfrom, 'to make', absto
     
try:
    join(fromdir, tofile)
except:
    print 'Error joining files:'
    print sys.exc_info()[0], sys.exc_info()[1]
else:
   print 'Join complete: see', absto
if interactive: raw_input('Press Enter key') # pause if clicked

希望本文所述对大家的Python程序设计有所帮助。

(0)

相关推荐

  • python简单分割文件的方法

    本文实例讲述了python简单分割文件的方法.分享给大家供大家参考.具体如下: 有的网站在上传文件时对文件大小有限制,因此可以将大文件分割成多个小文件再上传. #!/usr/bin/env python def split(filename, size): fp = open(filename, 'rb') i = 0 n = 0 temp = open(filename+'.part'+str(i),'wb') buf = fp.read(1024) while(True): temp.wri

  • Python实现分割文件及合并文件的方法

    本文实例讲述了Python实现分割文件及合并文件的方法.分享给大家供大家参考.具体如下: 分割文件split.py如下: #!/usr/bin/python ########################################################################## # split a file into a set of parts; join.py puts them back together; # this is a customizable ve

  • Python实现模拟分割大文件及多线程处理的方法

    本文实例讲述了Python实现模拟分割大文件及多线程处理的方法.分享给大家供大家参考,具体如下: #!/usr/bin/env python #--*-- coding:utf-8 --*-- from random import randint from time import ctime from time import sleep import queue import threading class MyTask(object): """具体的任务类"&qu

  • Python threading多线程编程实例

    Python 的多线程有两种实现方法: 函数,线程类 1.函数 调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么 复制代码 代码如下: # -*- coding: utf-8 -*- import thread def f(name):   #定义线程函数   print "this is " + name   if __name__ == '__main__':   thread.start_new_thread(f

  • 理解python多线程(python多线程简明教程)

    对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初步的认识. 单线程 在好些年前的MS-DOS时代,操作系统处理问题都是单任务的,我想做听音乐和看电影两件事儿,那么一定要先排一下顺序. (好吧!我们不纠结在DOS时代是否有听音乐和看影的应用.^_^) 复制代码 代码如下: from time import ctime,sleep def music():    for i in range(2):        prin

  • python多线程threading.Lock锁用法实例

    本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 复制代码 代码如下: mutex = threading.Lock() #锁的使用 #创建锁 mutex = threading.Lock() #锁定 mutex.acquire([timeout]) #释放 mutex.release() 锁定方法acquire可以有一个超时时间的可选参数timeout.如果设定了timeout,则在超时后通过返回值

  • python与php实现分割文件代码

    前两天有个朋友说,想实现一个文本文件按照固定行数进行分割成多个文本文件,却不知如何实现.如果数据量小手动分割下就好了,如果数据量很大的话手动完成实在太耗费人力了,也不现实.那么就需要借助脚本去实现.既然有朋友想简单的完成这个任务,那么不如记录下来,给需要的朋友提供方便. 下面我就分别使用python和php进行脚本的实现和操作,当然用其他语言都能实现,大家可根据对语言的熟悉程度进行自主选择,如果有朋友还没有达到编写代码的能力的话,那么最起码对语言环境的使用要会,只要达到这些,就可以完成如下工作.

  • Python实现将一个大文件按段落分隔为多个小文件的简单操作方法

    本文实例讲述了Python实现将一个大文件按段落分隔为多个小文件的简单操作方法.分享给大家供大家参考,具体如下: 今天帮同学处理一点语料.语料文件有点大,并且是以连续两个换行符作为段落标志,他想把它按段落分隔成多个小文件,即每3个段落组成一个新文件.由于以前没有遇到过类似的操作,在网上找了一些相似的方法,看起来都有点复杂.所以经尝试,自己写了一段代码,完美解决问题. 基本思路是,先读原文件内容,并使用正则表达式,依据\n\n进行切片处理,结果为一个列表,其中每一个列表元素都存放一个切片中的内容;

  • 详解Python中的多线程编程

    一.简介 多线程编程技术可以实现代码并行性,优化处理能力,同时功能的更小划分可以使代码的可重用性更好.Python中threading和Queue模块可以用来实现多线程编程. 二.详解 1.线程和进程        进程(有时被称为重量级进程)是程序的一次执行.每个进程都有自己的地址空间.内存.数据栈以及其它记录其运行轨迹的辅助数据.操作系统管理在其上运行的所有进程,并为这些进程公平地分配时间.进程也可以通过fork和spawn操作来完成其它的任务,不过各个进程有自己的内存空间.数据栈等,所以只

  • 浅析Python中的多进程与多线程的使用

    在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global interpreter lock(也被亲切的称为"GIL")指指点点,说它阻碍了Python的多线程程序同时运行.因此,如果你是从其他语言(比如C++或Java)转过来的话,Python线程模块并不会像你想象的那样去运行.必须要说明的是,我们还是可以用Python写出能并发或并行的代码,并且能带来性能的显著提升,只要你能顾及到一些事情.如果你还没看过的话,我建议你看看Eqbal Quran的文章

  • 用python分割TXT文件成4K的TXT文件

    复制代码 代码如下: ########################## # # # 为了避免截断中文字符 # # 文件要求是 unicode 编码 # # txt文件另存为对话框下面有下拉框,可选存 # # 储编码格式 # # # ########################## import os import struct filename = str(raw_input("Please enter an old file name: ")) filenamepre = s

随机推荐