working in rescue tar utility
[python-delta-tar] / filesplit.py
1 #!/usr/bin/env python
2
3 import argparse
4
5 BUFSIZE = 16 * 1024
6
7 def split_file(separator, prefix, input_file, new_file_func=None):
8     '''
9     splits a file when it finds a regexp, including the regexp in the begining
10     of the new file
11     '''
12     i = 0
13     pos = 0
14     buf = ""
15     sep_len = len(separator)
16     if sep_len == 0:
17         raise Exception("empty separator")
18
19     if new_file_func is None:
20         new_file_func = lambda prefix, i: open(prefix + str(i), 'w')
21
22     output = new_file_func(prefix, i)
23
24     # buffered search. we try not to have the while input file in memory, as
25     # it's not needed
26     with open(input_file, 'r') as f:
27         while True:
28             buf += f.read(BUFSIZE)
29             if len(buf) == 0:
30                 break
31
32             # split using the separator
33             while separator in buf:
34                 idx = buf.index(separator)
35
36                 if idx > 0:
37                     output.write(buf[0:idx])
38                     output.close()
39                     i += 1
40                     output = new_file_func(prefix, i)
41                     output.write(buf[idx:idx + sep_len])
42                 else:
43                     output.write(buf[0:sep_len])
44
45                 buf = buf[idx + sep_len:]
46
47             # corner case: separator is between this buf and next one. In this
48             # case, we write to current output everything before that and
49             # iterate
50             if separator[0] in buf[-sep_len:]:
51                 output.write(buf[:-sep_len])
52                 buf = buf[-sep_len:]
53                 continue
54
55             # else: continue writing to the current output and iterate
56             output.write(buf)
57             buf = ""
58
59     output.close()
60
61 if __name__ == "__main__":
62     parser = argparse.ArgumentParser()
63
64     parser.add_argument("-s", "--separator", required=True,
65                         help="string for the separator")
66     parser.add_argument("-p", "--prefix", required=True,
67                         help="prefix for split files")
68     parser.add_argument("input_file", help="input file")
69
70     args = parser.parse_args()
71     split_file(separator=args.separator, prefix=args.prefix, input_file=args.input_file)