为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

天涯尽头无女友 2023-09-05 19:46:20
使用Python 3.7 | WIN10我读过很多关于处理 python 中的路径的文章。尝试使用一个小脚本将所有文件和子目录文件按上次修改日期排序到文件夹中。到目前为止,它的工作原理都是为了一个问题,当获取子目录时,它会以 \ 开头返回,从而生成最终的目录字符串 base_dir/\subdir。这意味着第一组文件可以正常复制,但子目录中的任何内容都会失败。想要弄清楚如何阻止这种情况发生,我感到头疼。希望在屏幕中断后我能弄清楚,但以防万一,如果这里有任何向导可以提供帮助,我将不胜感激。代码:import osimport timeimport datetimeimport shutilfrom typing import List, TupleSORT_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_returndef 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)                continuefiles: List[Tuple] = []sort_files(SORT_DIR, files)print(files)
查看完整描述

1 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

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


我看到你正在将你的路径与:


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


查看完整回答
反对 回复 2023-09-05
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信