【问题标题】:Recursively move files from subdirectory to folders in parent directory递归地将文件从子目录移动到父目录中的文件夹
【发布时间】:2015-03-01 20:52:42
【问题描述】:

在以下目录中,

/Drive/Company/images/full_res/

存在 900 多个 .jpg 文件,如下所示:

Skywalker.jpg
Pineapple.jpg
Purple.jpg
White.jpg

在“full_res”(“images”)的上一级,存在的文件夹数量与“full_res”中的图像数量几乎相同,并且大部分都相应地命名,如下所示:

..
.
Skywalker/
Pineapple/
Purple/
White/
full_res/

我需要将 full_res 中的所有文件移动或复制到它们在“images”中相应命名的文件夹中,同时将文件重命名为“export.jpg”。结果应该是这样的:

/Drive/Company/images/
----------------------
..
.
Skywalker/export.jpg
Pineapple/export.jpg
Purple/export.jpg
White/export.jpg

This is the closest thing 我可以找到与我的查询相关的内容(我认为?),但我正在寻找一种使用 Python 执行此操作的方法。以下是我能够制作的任何东西:

import os, shutil

path = os.path.expanduser('~/Drive/Company/images/')
src = os.listdir(os.path.join(path, 'full_res/'))

for filename in src:
    images = [filename.endswith('.jpg') for filename in src]
    for x in images:
        x = x.split('.')
        print x[0] #log to console so I can see it's at least doing something (it's not)
        dest = os.path.join(path, x[0])
        if not os.path.exists(dest):
            os.makedirs(dest) #create the folder if it doesn't exist
        shutil.copyfile(filename, os.path.join(dest, '/export.jpg'))

这可能有很多问题,但我怀疑我最大的失败之一与我对列表理解概念的误解有关。无论如何,我已经为此苦苦挣扎了很长时间,以至于我现在可能已经自己手动移动并重命名了所有这些图像文件。感谢您提供任何和所有帮助。

【问题讨论】:

  • 看看images。它将是Trues 和Falses 的列表。

标签: python recursion directory list-comprehension


【解决方案1】:

你离正确答案不远了:

import os, shutil

path = os.path.expanduser('~/Drive/Company/images/')
src = os.listdir(os.path.join(path, 'full_res'))

for filename in src:
    if filename.endswith('.jpg'):
        basename = os.path.splitext(filename)[0]
        print basename #log to console so I can see it's at least doing something (it's not)
        dest = os.path.join(path, basename)
        if not os.path.exists(dest):
            os.makedirs(dest) #create the folder if it doesn't exist
        shutil.copyfile(os.path.join(path, 'full_res', filename), os.path.join(dest, 'export.jpg'))

【讨论】:

  • 搞定了,谢谢。我没有完全使用 .copyfile() 。干杯:)
猜你喜欢
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 2018-10-16
  • 2016-04-10
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多