將大量的文件平均分配到子文件夾下的python代碼

應用舉例:有10000個表格文件(都用規(guī)則的名稱命名,但是有的編號可能有遺漏),平均分配給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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容