遍历文件夹和子文件夹中的所有文件并获取创建日期

扬尼斯·帕帕斯蒂洛斯(Yannis Papastylos)

我正在尝试整理我的Photos文件夹,我认为我使用Python做到了。我要做的是浏览我的文件夹,检查每张照片(或视频)的扩展名,然后根据其创建日期将其移动到新位置。我从YouTube的视频中得到了这个主意。我还使用了代码。现在,以下代码一次完美地适用于一个文件夹:

from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, shutil


dir_path = "F:/Yannis/TestSortingFrom"
info_dict = {}
file_type_dict = {
    'CR2' : 'CR2',
    'CR3' : 'CR3',
    'dng' : 'DNG',
    'jpg' : 'JPG',
    'jpeg' : 'JPG',
    'JPG' : 'JPG',
    'bmp' : 'IMAGES',
    'png' : 'IMAGES',
    'ico' : 'IMAGES',
    'MP4' : 'Video',
    'mp4' : 'Video',
    'avi' : 'Video',
    'mov' : 'Video',
    }
destination_path = "F:/Yannis/SortingDestination/"
year_exists = False
month_exists = False


data = (os.path.join(dir_path, fn) for fn in os.listdir(dir_path))
data = ((os.stat(path), path) for path in data)


data = ((stat[ST_CTIME], path)
           for stat, path in data if S_ISREG(stat[ST_MODE]))
for cdate, path in sorted(data):
    info_dict.update({os.path.basename(path): time.ctime(cdate) })
for key, value in info_dict.items():
    file_date = value.split()
    file_extension = key.split(".")
    for key2, value2 in file_type_dict.items():
        if file_extension[1] == key2:
            destination_folder = destination_path +value2
            for folder_name in os.listdir(destination_folder):
                if folder_name == file_date[4] :
                    destination_folder1 = destination_folder +'/' + folder_name
                    year_exists = True
                    for folder_month in os.listdir(destination_folder1):
                        if folder_month == file_date[1]:
                            destination_folder2 = destination_folder1 + '/' + folder_month
                            month_exists = True
                            FROM = dir_path + '/' + key
                            TO = destination_folder2 + '/' + key
                            shutil.move(FROM, TO)
            if not year_exists:
                os.mkdir(destination_path + value2 + '/' + file_date[4])
                destination_folder1 = destination_path + '/' + value2 + '/' + file_date[4]

            if not month_exists:
                os.mkdir(destination_path + value2 + '/' + file_date[4] + '/' + file_date[1])
                destination_folder2= destination_path + value2 + '/' + file_date[4] + '/' + 
                                     file_date[1]
                FROM = dir_path + '/' + key
                TO = destination_folder2 + '/' + key
                shutil.move(FROM, TO)

    destination_folder2 = destination_path + '/' + 'Uncategorized'
    FROM = dir_path + '/' + key
    TO = destination_folder2 + '/' + key
    shutil.move(FROM, TO)

我尝试了以下方法来遍历文件夹树,但它返回FileNotFound错误。

for dirname, dirnames, filenames in os.walk('F:/Yannis/TestSortingFrom'):
        for subdirname in dirnames:
            dirpath = os.path.join(dirname, subdirname)

我用dirpath替换了先前代码中的dir_path

你有什么想法?因为我茫然。我可以一次只处理一个文件,但我想简单地指定一个文件夹并完成它可能会很棒。

错误消息如下:

Traceback (most recent call last):
File "C:\Users\Yannis\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 566, in move os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 
'F:/Yannis/TestSortingFrom\\Camera/IMG_20110305_143031.jpg' -> 
'F:/Yannis/SortingDestination//Uncategorized/IMG_20110305_143031.jpg'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
File "G:/Python/PyCharmProjects/FileSorting/test.py", line 68, in <module> shutil.move(FROM, TO)
File "C:\Users\Yannis\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 580, in move copy_function(src, real_dst)
File "C:\Users\Yannis\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 266, in copy2 copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\Yannis\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 120, in copyfile with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 
'F:/Yannis/TestSortingFrom\\Camera/IMG_20110305_143031.jpg'

编辑:现在以下代码工作(某种)。奇怪的是,如果我的origin_path具有子目录,则程序会将文件从第一个子目录移走,而其他文件则保持完整。如果我第二次运行它,它将文件从第二个子目录中移出,依此类推。另一个奇怪的行为是,如果不同类型的文件(在我的情况下为.jpg,.JPG,.dng,.mp4)位于同一子目录中,则程序将移动除.mp4以外的所有文件。如果我第二次运行它,它也会移动.mp4。修改后的代码是:

from pathlib import Path
import os, time, shutil
from stat import S_ISREG, ST_CTIME, ST_MODE


class fileToMove():
    def __init__(self, name, folder, date):
        self.name = name
        self.folder = folder
        self.date = date


info_list = []
info_dict = {}
file_type_dict = dict(CR2 = 'CR2', CR3 = 'CR3', dng = 'DNG', jpg = 'JPG',     jpeg = 'JPG', JPG = 'JPG', bmp = 'IMAGES',
                  png = 'IMAGES', ico = 'IMAGES', mp4 = 'Video', MP4 = 'Video', avi = 'Video', mov = 'Video')
destination_path = Path("F:/Yannis/SortingDestination/")
origin_path = Path('F:/Yannis/TestSortingFrom/')
year_exists = False
month_exists = False

for dirname, dirnames, filenames in os.walk(origin_path):
    for subdirname in dirnames:
        dirpath = os.path.join(dirname, subdirname)
        data = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
        data = ((os.stat(path), path) for path in data)
        data = ((stat[ST_CTIME], path) for stat, path in data if S_ISREG(stat[ST_MODE]))
        for cdate, path in sorted(data):
            fl = fileToMove(os.path.basename(path), path, time.ctime(cdate))
            info_list.append(fl)
for filez in info_list:
    file_date = str(filez.date).split()
    file_name = str(filez.name).split('.')
    file_folder = str(filez.folder)
    print(filez.date, filez.folder, filez.name, file_name)
    for key, value in file_type_dict.items():
        if key == file_name[1]:
                destination_folder = destination_path / value
                for folder_name in os.listdir(destination_folder):
                    if folder_name == file_date[4]:
                        destination_folder1 = destination_folder / folder_name
                        year_exists = True
                        for folder_month in os.listdir(destination_folder1):
                            if folder_month == file_date[1]:
                                month_exists = True
                                FROM = file_folder
                                TO = destination_folder1 / folder_month / filez.name
                                shutil.move(FROM, TO)
                if not year_exists:
                    os.mkdir(destination_path / value / file_date[4])
                if not month_exists:
                    os.mkdir(destination_path / value / file_date[4] / file_date[1])
                    destination_folder2 = destination_path / value / file_date[4] / file_date[1]
                    FROM = file_folder
                    TO = destination_folder2 / filez.name
                    shutil.move(FROM, TO)
扬尼斯·帕帕斯蒂洛斯(Yannis Papastylos)
from pathlib import Path
import os, time, shutil
from stat import S_ISREG, ST_CTIME, ST_MODE


class fileToMove():
    def __init__(self, name, folder, date):
        self.name = name
        self.folder = folder
        self.date = date

info_list = []
info_dict = {}
file_type_dict = dict(CR2 = 'CR2', CR3 = 'CR3', dng = 'DNG', jpg = 'JPG', jpeg = 'JPG', JPG = 'JPG', bmp = 'IMAGES',
                  png = 'IMAGES', ico = 'IMAGES', mp4 = 'Video', MP4 = 'Video', avi = 'Video', mov = 'Video')
destination_path = Path("F:/Yannis/SortingDestination/")
origin_path = Path('F:/Yannis/Photos/2019/9-2-2019/')

for dirname, dirnames, filenames in os.walk(origin_path):
    for subdirname in dirnames:
        dirpath = os.path.join(dirname, subdirname)
        data = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
        data = ((os.stat(path), path) for path in data)
        data = ((stat[ST_CTIME], path) for stat, path in data if S_ISREG(stat[ST_MODE]))
        for cdate, path in sorted(data):
            fl = fileToMove(os.path.basename(path), path, time.ctime(cdate))
            info_list.append(fl)
            print(fl.date)
for filez in info_list:
    file_date = str(filez.date).split()
    file_name = str(filez.name).split('.')
    file_folder = str(filez.folder)
    if file_name[1] not in file_type_dict:
        destination_folder3 = destination_path / 'Uncategorized'
        FROM = file_folder
        TO = destination_folder3 / filez.name
        shutil.move(FROM, TO)
    else:
        for key, value in file_type_dict.items():
            if key == file_name[1]:
                year_exists = False
                month_exists = False
                day_exists = False
                destination_folder = destination_path / value
                for folder_year in os.listdir(destination_folder):
                    if folder_year == file_date[4]:
                        destination_folder_year = destination_folder / folder_year
                        year_exists = True
                        for folder_month in os.listdir(destination_folder_year):
                            if folder_month == file_date[1]:
                                destination_folder_month = destination_folder_year / folder_month
                                month_exists = True
                                for folder_day in os.listdir(destination_folder_month):
                                    if folder_day == file_date[2]:
                                        day_exists = True
                                        FROM = file_folder
                                        TO = destination_folder_year / folder_month / folder_day / filez.name
                                        shutil.move(FROM, TO)
                if not year_exists:
                    os.mkdir(destination_path / value / file_date[4])
                if not month_exists:
                    os.mkdir(destination_path / value / file_date[4] / file_date[1])
                if not day_exists:
                    os.mkdir(destination_path / value / file_date[4] / file_date[1] / file_date[2])
                    destination_folder2 = destination_path / value / file_date[4] / file_date[1] /file_date[2]
                    FROM = file_folder
                    TO = destination_folder2 / filez.name
                    shutil.move(FROM, TO)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

获取文件夹和子文件夹中的所有文件

C# sharepoint 循环遍历文件夹和所有子文件夹中的所有文件

获取文件夹和子文件夹中所有.txt文件的路径

递归清除其中没有文件的文件夹中的所有文件夹和子文件夹

读取文件夹和子文件夹中的所有文件-进度和大小

为文件夹和子文件夹中的所有文件设置命名空间

将文件复制到文件夹和所有子文件夹中

Gitignore用于文件夹和子文件夹中的所有文件

批。批量重命名文件夹和所有子文件夹中的文件

Powershell 查找给定文件夹名称中的所有空文件夹和子文件夹

获取文件夹中所有文件的绝对路径,不遍历子文件夹

PowerShell - 列出 TreeView GUI 元素中的所有文件夹和子文件夹

遍历所有文件夹及其所有子文件夹VBA

如何忽略提名文件夹中的_vti_cnf和_vti_pvt文件夹以及提名文件夹的所有子文件夹?

.htaccess规则文件与所有子文件夹匹配(子文件夹是随机创建的)

如何遍历文件夹并从分组的子文件夹中获取某些文件?

如何遍历所有Assets文件夹和子文件夹并获得该文件夹中所有预制件的列表?

遍历文件夹并使用文件夹名称顺序重命名每个文件夹中的所有文件

MVC创建“文件夹”和子文件夹

循环遍历文件夹中的所有 .csv 文件

遍历Python文件夹中的所有文件

从文件夹中的所有文件创建zip文件

在 Google Apps Script 中,如何获取所有子文件夹和所有子子文件夹以及所有子子子文件夹等?

Powershell:将所有文件从文件夹和子文件夹移至单个文件夹

在当前日期创建的文件夹和子文件夹中查找文件

列出R中没有子文件夹的文件夹中的所有文件

如何在SSIS中基于文件夹的创建日期读取文件夹的所有文件?

删除所有旧文件,文件夹和子文件夹的命令

Git将文件夹视为文件,并忽略所有子文件夹和-files