找尋多個文件夾中最新檔案(jpg,png,txt)並複製到nexus資料夾

URL Link //n.sfs.tw/13121

2019-02-21 14:16:37 By igogo

 

目的

從一csv 清單中, 找尋使用者名單, 依此名單去找每個使用者所放置的最新檔案, 數目不等, 需依csv裡設定值

檔案類型包括jpg, png, txt  , 再複製每個user給的額度數目到特定資料夾

 

namelist.csv

igogo,10
mary,2

 

建立Model User

class User:
    name = ""
    quota = 0
    userDir = ""
    userFiles = []

    def _init_(self):
        pass

    def setName(self, name):
        self.name = name

    def getName(self):
        return self.name

    def setUserdir(self, userDir):
        self.userDir=userDir

    def getUserDir(self):
        return self.userDir

    def setQuota(self, quota):
        self.quota = int(quota)

    def getQuota(self):
        return self.quota

    def setFiles(self, userFiles):
        self.userFiles = userFiles

    def getFiles(self):
        return self.userFiles

 

main.py

import os
import csv
import pathlib
import glob
import shutil
from model import User


def getTargetFiles(files, quota):
    targetFiles = []
    if (len(files) > quota):
        for i in range(0, quota):
            targetFiles.append(files[i])
        return targetFiles;
    else:
        return files


cwd = os.path.dirname(os.path.realpath(__file__))
csvFile = cwd + '/namelist.csv'

nexusDir = "/home/public/led/nexus"
namelist = []
with open(csvFile) as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    for row in csvreader:
        user = User();
        user.setName(row[0])
        user.setQuota(row[1])

        namelist.append(user)

for user in namelist:
    userDir = "/home/public/led/{}/".format(user.getName())
    user.setUserdir(userDir)
    if (os.path.isdir(userDir)) == True:
        files = glob.glob(os.path.join(userDir, '*.jpg'))
        files.extend(glob.glob(os.path.join(userDir, '*.txt')))
        files.extend(glob.glob(os.path.join(userDir, '*.png')))
        files.sort(key=os.path.getmtime, reverse=True)
        targetFiles = []
        if len(files) != 0:
            user.setFiles(getTargetFiles(files, user.getQuota()))

if (os.path.isdir(nexusDir)) == True:
    shutil.rmtree(nexusDir)
    os.mkdir(nexusDir)
else:
    os.mkdir(nexusDir)

for user in namelist:
    for userFile in user.getFiles():
        dest = "{}/{}-{}".format(nexusDir, user.getName(), os.path.basename(userFile))
        print(dest)
        shutil.copy(userFile, dest)