summaryrefslogtreecommitdiffstats
path: root/combox/utils/file.py
blob: bb2759276dbc5eeb81528bcbd1cd3088860b7cf3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#    Copyright (C) 2014 Combox author(s). See AUTHORS.
#
#    This file is part of Combox.
#
#   Combox is free software: you can redistribute it and/or modify it
#   under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   Combox is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#   General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with Combox (see COPYING).  If not, see
#   <http://www.gnu.org/licenses/>.

from os import path
from sys import exit


def split_file(filename, n):
    """Split the file into `n' parts and return them as an array.

    filename: Absolute pathname of the file.
    n: Number of parts the file has to be split.
    """

    file_ = None
    try:
      file_   = open(filename, 'rb')
    except IOError:
        print "ERROR: opening %s" % (filename)
        exit(1)

    f_parts = []
    # File size in bytes.
    file_size = path.getsize(filename)
    # No. of bytes for each file part.
    part_size =  file_size / n
    # Take note of remaining bytes; this is non-zero when file_size is
    # not divisible by `n'.
    rem_bytes = file_size % n

    i = 0
    while i < n:
        f_parts.append(file_.read(part_size))
        i += 1

    # read the remaining bytes into the last file part.
    f_parts[n-1] += file_.read(rem_bytes)

    return f_parts


def glue_file(f_parts):
    """Glue different parts of the file to one.

    f_parts: Array containing different parts of the file. Each part
    is a sequence of bytes.
    """

    file_content = ''
    for part in f_parts:
        file_content += part

    return file_content


def write_file(filename, filecontent):
    """Write `filecontent' to `filename'.

    filename: Absolute pathname of the file.
    filecontent: String/bytstream to write to filename.
    """

    file_ = None
    try:
      file_   = open(filename, 'wb')
      file_.write(filecontent)
    except IOError:
        print "ERROR: creating and writing content to %s" % (filename)
        exit(1)