子目录中的python文件路径不正确

狂怒

编辑:使用 Python 3.7 | 赢10

我已经阅读了很多关于在 python 中处理路径的帖子。尝试编写一个小脚本,按上次修改日期将所有文件和子目录文件分类到文件夹中。

到目前为止,它的工作原理是一个问题,当获取子目录时,它以 \ 开头返回,从而使最终目录字符串 base_dir/\subdir。

这意味着第一组文件被复制得很好,但子目录中的任何内容都失败了。

试图弄清楚如何阻止这种情况发生时感到头疼。希望在屏幕中断后我会弄清楚,但以防万一,如果这里有任何向导可以提供帮助,我们将不胜感激。

代码:

import os
import time
import datetime
import shutil
from typing import List, Tuple


SORT_DIR = r'to_sort/'


def date_from_seconds(file_stats):
    """
    Takes an os.stats variable and return a date
    Using the seconds elapsed since last modification
    """
    
    seconds = time.ctime(file_stats.st_mtime)
    date_filter = datetime.datetime.strptime(seconds, '%a %b %d %H:%M:%S %Y')
    date_to_return = f'{date_filter.day}-{date_filter.month}-{date_filter.year}'
    
    return date_to_return


def sort_files(path_directory: str, file_list: List[Tuple]):
    """
    Lists the files in the sort directory
    Uses recursion to obtain files from subdirectories
    Copies files to a directory named according to their last modified date
    """

    content_dir: List[str] = os.listdir(path_directory)

    for filename in content_dir:
        path_file = os.sep.join([path_directory, filename])
        if os.path.isdir(path_file):
            sort_files(path_file, file_list)
        else:
            try:
                stats = os.stat(path_file)
                date = date_from_seconds(stats)
                file_list.append((path_directory, filename, date))
                os.makedirs(date, exist_ok=True)
                print(f'{path_directory}{filename}')
                shutil.copy(f'{path_directory}{filename}', f'{date}/{filename}')
            except Exception as _err:
                print(_err)
                continue


files: List[Tuple] = []
sort_files(SORT_DIR, files)
print(files)

输出:

subdir_sort.py
to_sort/1001001.jpg
to_sort/1001002.jpg
to_sort/1001003.jpg
to_sort/\subdir1002007.jpg
[Errno 2] No such file or directory: 'to_sort/\\subdir1002007.jpg'
to_sort/\subdir1002010.jpg
[Errno 2] No such file or directory: 'to_sort/\\subdir1002010.jpg'
to_sort/\subdir1002021.jpg
[Errno 2] No such file or directory: 'to_sort/\\subdir1002021.jpg'
[('to_sort/', '1001001.jpg', '21-9-2020'), ('to_sort/', '1001002.jpg', '21-9-2020'), ('to_sort/', '1001003.jpg', '21-9-2020'), ('to_sort/\\subdir', '1002007.jpg', '16-9-2020'), ('to_sort/\\subdir', '1002010.jpg', '16-9-2020'), ('to_sort/\\subdir', '1002021.jpg', '16-9-2020')]

Process finished with exit code 0

谢谢!

编辑:来自 orlevii 的回答很有用..这是更正后的代码:

def sort_files(path_directory: str, file_list: List[Tuple]):
    """
    Lists the files in the sort directory
    Uses recursion to obtain files from subdirectories
    Copies files to a directory named according to their last modified date
    """

    for data in os.walk(SORT_DIR):
        dir_path, folders, files = data
        print(dir_path)
        print(files)
        for file in files:
            try:
                dir_for_stat = f'{dir_path}\{file}'
                stats = os.stat(dir_for_stat)
                date = date_from_seconds(stats)
                file_list.append((dir_path, file, date))
                os.makedirs(date, exist_ok=True)
                print(f'{dir_path}\{file}')
                shutil.copy(f'{dir_path}\{file}', f'{date}\{file}')
            except Exception as _err:
                print(_err)
                continue
奥尔列维

你在什么操作系统上运行?

我看到你正在连接你的路径:

path_file = os.sep.join([path_directory, filename])

如果您使用的是 Windows,这是错误的。

为了使其正常工作,您可以使用

path_file = os.path.join(path_directory, filename)

2,您自己实施扫描有什么原因吗?

您可以使用os.walk从给定的根路径开始获取所有文件/目录:

import os

SORT_DIR = 'to_sort'

for data in os.walk(SORT_DIR): # where to start searching
    dir_path, folders, files = data
    # Now do whatever you want with the `files` variable

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何获取子目录中包含特定目录字符串的子目录中python文件的路径

如何正确指定路径以从我的项目的子目录中打开文件?

子目录中的foreach python文件

相对于Python中的父目录设置子目录的文件的工作路径

chm文件中的目录不正确

批处理脚本:命令的语法不正确-当脚本通过子目录时?

Laravel:将文件存储在strorage路径的子目录中

如何遍历目录中的子目录并计算python中子目录中的文件

将名称不正确的文件从一个深层嵌套的目录(内容地址重命名)复制到一个Bash单行格式的另一个扁平子目录中?

子目录中的文件?

如何在批处理文件中引用子目录,该子目录的路径取决于用户帐户?

在Python中更改的子目录中查找文件

如何在python中包含给定路径中的所有文件以及子目录的所有文件?

仅使用python查找子目录中的文件

Python os.walk,处理子目录中的文件

在Docker子目录中运行python文件

如何从Java中的路径获取目录和子目录中的文件数?

如何在目录及其子目录中列出某些文件类型的完整路径?

查找目录路径不包含子目录的文件

忽略子目录中的gitignore文件

在子目录中创建同名文件

Git忽略了子目录中的文件

如何删除子目录中的文件

忽略子目录中的文件?

子目录中的Wordpress模板文件

在 zip 的子目录中添加文件

在子目录中递归移动文件

检查文件是否在子目录中?

在子目录中查找文件