【问题标题】:Python move dynamic subfolder one folder upPython将动态子文件夹上移一个文件夹
【发布时间】:2021-11-17 20:05:04
【问题描述】:

我们有一个文件共享,其中填充了平面文件。提取文件的过程已将文件提取到 XYZ/YEAR/DAY/MONTH/x/y/z/files 文件夹结构中。这是错误的,因为它需要采用以下结构:XYZ/YEAR/MONTH/DAY/x/y/z/files。因此,我们需要创建一个迁移脚本,以某种方式将所有文件从旧结构移动到新结构。

谁能给我一些指示如何用 Python 做到这一点?我已经能够使用 os 模块列出所有文件和子目录,但不知道如何将子文件夹按天和按月移动到目标结构。

提前致谢!

我必须补充一点:将月份文件夹重命名为日期文件夹也可以,反之亦然。

【问题讨论】:

  • 这些都是数字吗?也就是“XYZ/2021/17/11”?
  • 我认为您应该问的问题是“如何将字符串 "XYZ/YEAR/DAY/MONTH/x/y/z/files" 更改为 "XYZ/YEAR/MONTH/DAY/x/y/z/files"?”。一旦你弄清楚了,问题就变成了“如何将所有文件从文件夹 A 移动到文件夹 B?”将问题分解成更小的部分,很容易找到解决方案。

标签: python os.walk


【解决方案1】:

这应该做你想做的事。这有点危险,因此您可能需要注释掉 os.mkdiros.renameos.rmdir 操作,并在第一次用 print 语句替换它们,以确保它做正确的事情。

这是一个棘手的问题。您不能只将“01”移动到年份目录,因为第 1 天已经有一个“01”。在这里,我创建带有前缀(“m01”、“m02”等)的月份目录,然后移动内容,然后删除日目录并重命名月目录。

现在我想起来了,创建另一个“年份”树可能更容易,但我认为这会奏效。

import os

os.chdir( "XYZ" )


for year in os.listdir('.'):
    if not os.path.isdir(year):
        continue

    # Create month directories with an "m" prefix.

    for mon in range(1,13):
        os.mkdir( f"{year}/m{mon:02d}" )

    # For each day, move the contents.

    for day in os.listdir(year):
        yydd = os.path.join(year,day)
        if not os.path.isdir(yydd):
            continue
        for mon in os.listdir(yydd):
            yyddmm = os.path.join(year,day,mon)
            yymmdd = os.path.join(year,f"m{mon:02d}",day)
            os.mkdir( yymmdd )
            for part in os.listdir(yyddmm):
                os.rename( yyddmm+"/"+part, yymmdd )
    
    # Should now be able to delete the old structure for this year,
    # assuming they are empty.

    for day in os.listdir(year):
        if day[0] == 'm':
            continue
        yydd = os.path.join(year,day)
        for mon is os.listdir(yydd):
            os.rmdir( yydd+"/"+mon )
        os.rmdir( yydd )

    # Remove the prefix.

    for mon in range(1,13):
        os.rename( f"{year}/m{mon}", f"{year}/{mon}" )

【讨论】:

    猜你喜欢
    • 2022-10-25
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 2011-04-24
    • 2016-01-25
    相关资源
    最近更新 更多