首页 > 解决方案 > 根据创建日期和文件夹名称 Python 将文件移动到文件夹

问题描述

我对 Python 很陌生,但我有一个非常有趣的案例,它可能会为我们所有人提供学习的东西。我想做以下事情。我在桌面上创建了 3 个文件夹(源、目标和存档)。所有 3 个文件夹都包含相同的 3 个子文件夹(A、B 和 C)。Source 中的 3 个子文件夹时不时地被文件填满。Destination 和 Archive 为空(暂时)。

现在我想创建一个文件管理系统,每次运行代码时都会执行以下操作:

  1. Python 检查 Source 中的每个子文件夹(A、B、C),存在多少文件。如果 Source 中的子文件夹 (A,B,C) 中至少存在一个文件,则:

只有 Source 中 3 个子文件夹(A、B、C)中最后创建的文件会被移动到 Destination 中的 3 个子文件夹(A、B、C)中。这意味着每次我运行代码时,源中子文件夹 A 中的最新文件将被移动到目标中的子文件夹 A(等等。对于 B 和 C)。但是,仅当文件至少存在 5 分钟时才会进行移动。所以如果一个文件是在 1 分钟前创建的,它就不会移动。

如果还有剩余的文件(不是最后创建的),那么它将被移动到存档中的子文件夹(A、B、C)。

请注意,每次移动文件时,都必须将其放入与其先前位置同名的子文件夹中。因此,子文件夹 A 中的文件永远不能移动到子文件夹 B。

这是我现在拥有的代码,但我得到了无效的语法。代码可能不完整。

from datetime import datetime,timedelta
import shutil, os

#Creating Source, Destination and Archive paths.
source = r'c:\data\AS\Desktop\Source'
destination = r'c:\data\AS\Desktop\Destination'
archive = r'c:\data\AS\Desktop\Archive'

mod_time = timedelta(minutes=5)
now = datetime.now()
before = now - mod_time

for root, dirs, files in os.walk(source):
   for file in dirs:
       if file > before:
           shutil.move(file, destination)
        else file:
            shutil.move(file, destination)

标签: pythonfilefile-handlingshutil

解决方案


好吧,我只是一个初学者,但这是我对您的问题的尝试:

import shutil, os
import time
#Creating Source, Destination and Archive paths.
source = r'C:\python\here\source'
destination = r'C:\python\here\destination'
archive = r'C:\python\here\archive'

#Current time in seconds
current_time=time.time()

#First os.walk for the source folder itself
for root, dirs, files in os.walk(source):
    for folder in dirs:
        subdir=root+'\\'+folder
        #second os.walk for each folder in the source folder (A, B, and C)
        for subroot, subdirs, subfiles in os.walk(subdir):
            for file in subfiles:
                filePath=subroot+'\\'+file
                #Gets the file descriptor and stores it in fileStat
                fileStat = os.stat(filePath)
                #st_ctime is the files creation time.
                #current time in seconds - file creation would be the difference 
                #between the current time and the file creation time.
                #Divide by 60 to convert that to minutes.
                ######################################
                ##If time passed greater than 5 minutes, send to a matching folder in destination
                if ((current_time-fileStat.st_ctime)/60) > 5: 
                    shutil.move(filePath,destination+'\\'+folder)
                else:
                    shutil.move(filePath,archive+'\\'+folder)

注意:在每个文件夹源、目标和存档中,我创建了子文件夹 A、B 和 C。


推荐阅读