应用举例:有10000个表格文件(都用规则的名称命名,但是有的编号可能有遗漏),平均分配给n个人
如下的代码可以自动生成子文件夹(sub1,sub2,。。。,subn)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script splits multiple files into segregated folders averagely.
Usage: python seperate.py source destination groupNumber folderFormat
Example: python seperate.py /source /destination 3 sub, which groups files in /source into /destination/sub001/, /destination/sub002/ and /destination/sub003/
Notice subdirectories should be avoided in /source/
"""
import sys
import os
import math
def normalisePath(path):
'''
Add a slash at the end of path if not end with a slash
'''
if path.endswith('/'):
return path
else:
return (path + '/')
def copy(source, des):
'''
Copy file from source to destination
'''
if os.path.exists(source):
os.system("cp " + source + " " + des)
path_source = normalisePath(sys.argv[1])
path_des = normalisePath(sys.argv[2])
group_number = int(sys.argv[3])
folderFormat = sys.argv[4]
files = os.listdir(path_source)
files.sort() # Sort the files by their name
N = len(files)
group_length = math.ceil(N / group_number)
group = 1
flag = 0 # create a new sub directory when flag is zero
for i in range(1, N + 1):
path_des_subdir = normalisePath(path_des + folderFormat + str(group))
if flag == 0:
os.mkdir(path_des_subdir)
flag = 1
file_source = path_source + files[i - 1]
file_des = path_des_subdir + files[i - 1]
copy(file_source, file_des)
if i % group_length == 0:
flag = 0
group = group + 1