-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjoin_part_files.py
59 lines (53 loc) · 1.74 KB
/
join_part_files.py
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
#!/usr/bin/env python
#
# Script to join numbered part files.
import sys
import os
import re
import shutil
drop_dir = '/volume1/Download/NZBGet/dst'
def join_part_files(dir_path):
all_files = os.listdir(dir_path)
prefix = os.path.commonprefix(all_files).rstrip('.')
pattern = re.compile('^' + re.escape(prefix) + r'(\.[0-9]{3})?$')
part_files = sorted(x for x in all_files if pattern.match(x))
if len(part_files) < 2:
print 'No part files found in:', dir_path
return False
if prefix in part_files and prefix + '.000' in part_files:
print 'Error: Ambiguous part files in:', dir_path
return False
prefix_path = os.path.join(dir_path, prefix)
joining_path = prefix_path + '.joining'
try:
with open(joining_path, 'wb') as out:
for part_name in part_files:
print 'Joining:', part_name
with open(os.path.join(dir_path, part_name), 'rb') as part:
shutil.copyfileobj(part, out)
except Exception:
try:
os.remove(joining_path)
except OSError:
pass
raise
for part_name in part_files:
try:
os.remove(os.path.join(dir_path, part_name))
except OSError as e:
print 'Error removing part file:', e
os.rename(joining_path, prefix_path)
return True
def join_part_files_in_dirs(dir_path):
for filename in sorted(os.listdir(dir_path)):
path = os.path.join(dir_path, filename)
if os.path.isdir(path):
join_part_files(path)
def main():
if len(sys.argv) == 1:
join_part_files_in_dirs(drop_dir)
else:
for path in sys.argv[1:]:
join_part_files(path)
if __name__ == '__main__':
main()