将文件重命名为子目录中的年份而不是子目录 [英] Rename files to instead being in sub-directories, have the year as part of the filename

查看:121
本文介绍了将文件重命名为子目录中的年份而不是子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个名为CarItemsCopy的CarItems树的副本,其中所有文件都位于文件名的一部分中,而没有年份,而是以年作为名称,而年目录则完全不存在。
代替以下示例:

Create a copy of the CarItems tree called CarItemsCopy where all files, instead of being in directories named after years, rather have the year as part of the filename, and the year directories are entirely absent. Instead of some of these examples:

CarItems/Chevrolet/Chevelle/2011/parts.txt
CarItems/Chevrolet/Chevelle/1982/parts.txt
CarItems/Chevrolet/Volt/1994/parts.txt

它应该看起来像这样:

CarItemsCopy/Chevrolet/Chevelle/parts-2011.txt
CarItems/Chevrolet/Chevelle/parts-1982.txt
CarItems/Chevrolet/Volt/parts-1994.txt

使用Python执行此操作(您无法通过手动重新排列来创建副本)。您可以使用os模块的步进生成器。提示:您可能会发现os.path模块的split函数会有所帮助。

Do this using Python (you can't create the copy by manually rearranging things). You may use the os module's walk generator. Hint: You might find the os.path module's split function to be helpful. You don't have to use it though.

这是我到目前为止获得的代码:

This is the code I have got so far:

def create_dir(dir_path):
""" Creates a new directory.

This function is used to create a new directory.

Positional Input Parameter:
    directory: Car
Keyword Input Parameters:
    None    
"""
    if not os.path.exists(dir_path):
        former_path, sub_dir = os.path.split(dir_path)

        if os.path.exists(former_path) or former_path == "":
            os.mkdir(dir_path)
        else:
            create_dir(former_path)
            os.mkdir(dir_path) 

    for dirpath, dirname, filename in os.walk("CarItems"):
        if len(filename) > 0:
            sub_path, year = os.path.split(dirpath)

        for i in filename:
            name, suffix = os.path.splitext(i)
            new_file = name + "-" + year + suffix

            new_path = sub_path.replace("CarItems", "CarItemsCopy")
            create_dir(new_path)

            file_path = os.path.join(dirpath, i)
            new_file_path = os.path.join(new_path, new_file)

            shutil.copy2(file_path, new_file_path)

FileNotFoundError:[错误2]没有这样的文件或目录:''
这是我遇到的错误Mac,在Windows上可以完美运行。
我的问题是为什么,要在Mac上运行需要进行哪些调整?
谢谢!

FileNotFoundError: [Errno 2] No such file or directory: '' this is the error I'm getting on a Mac, on a windows it works perfectly. My question, why is that, and what adjustment would need to be made for it to work on a mac? Thanks!

推荐答案

应该是什么样的部分中,我认为您做了一个失误。 CarItemsCopy 下仅存在一个目录,另一个目录将被重命名。

In the what it should look like section I think you made a mistake. Only one directory will exist under CarItemsCopy, the other will be renamed where they're located.

任务

创建的副本CarItems 树,名为 CarItemsCopy ,其中所有文件而不是位于以年命名的目录中,而是将年作为文件名的一部分,并将年目录完全不存在。

Create a copy of the CarItems tree called CarItemsCopy where all files, instead of being in directories named after years, rather have the year as part of the filename, and the year directories are entirely absent.

路径 shutil ,并且 os 模块应该简化任务:

The path, shutil, and os modules should simplify the task:

from pathlib import Path
import os
from shutil import copy2

# Place this script in the CarItems folder.    

# The full path to our CarItems folder.
script_dir = Path(os.path.dirname(os.path.abspath(__file__)))
source_dir = script_dir.joinpath("Caritems")

for folder in source_dir.iterdir():
    for subfolder in folder.iterdir():
        subfolder_with_parts = subfolder.joinpath("parts.txt")
        if subfolder_with_parts.exists(): # Only continue if parts.txt exists.
            ext = subfolder_with_parts.suffix # In this case .txt
            parts = Path(f"CarItemsCopy//{folder.stem}//parts-{subfolder.stem}{ext}")
            car_copy = script_dir.joinpath(parts)
            car_copy.parent.mkdir(parents=True, exist_ok=True)
            copy2(subfolder_with_parts, car_copy) # Will attempt to copy the metadata.

这篇关于将文件重命名为子目录中的年份而不是子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆