A common way to split files in python

  • 2020-04-02 14:15:56
  • OfStack

In this article, we have compiled some useful methods about python file segmentation, the method is very simple and practical. Share with you for your reference. The details are as follows:

Example 1 specifies the split file size

Config. Ini:

[global]
# The original file is stored in the directory
dir1=F:workpython3595pyservertest
# New files are stored in the directory
dir2=F:workpython3595pyservertest1

The python code is as follows:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys,ConfigParser
class file_openate(object):
def __init__(self):
    # Initially read the database configuration
    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=" Software has uncertainty , It's best to back up before using it , Avoid data loss , After confirming the backup , Please enter the size of the bytes to be split , According to the b To calculate the ".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 " Segmentation success ".decode('utf-8') + filename
f.close()
else:
    print " Please enter the correct number , Please re-enter ".decode('utf-8')
file_name=file_openate()
file_name.file_list()

Example 2, split the file size by line

#!/usr/bin/env python
#--*-- coding:utf-8 --*--
import os
class SplitFiles():
    """ Split the file by line """
    def __init__(self, file_name, line_count=200):
        """ Initializes the source file name to be split and the number of lines in the split file """
        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 : # use with Read the file
                    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 : # Write the rest to a new file after the loop is normally closed
                        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):
        """" Gets the split file name: creates a temporary folder in the same directory as the source file temp_part_file , and then put the split file under that path """
        temp_path = os.path.dirname(self.file_name) # Get the path to the file (not including the file name)
        part_file_name = temp_path + "temp_part_file"
        if not os.path.exists(temp_path) : # If the temporary directory does not exist, it is created
            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):
        """ Writes the split by line to the corresponding split file """
        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()

It's just split up, what if we want to merge again? The following example can achieve segmentation and merge oh, let's see together.

Example 3, split file and merge function

#!/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

I hope this article has helped you with your Python programming.


Related articles: