【问题标题】:python: collect files with one extention from all sub-dirpython:从所有子目录中收集具有一个扩展名的文件
【发布时间】:2020-05-20 03:36:39
【问题描述】:

我正在尝试收集所有子目录的所有文件并移动到另一个目录

使用的代码

#collects all mp3 files from folders to a new folder
import os
from pathlib import Path
import shutil


#run once
path = os.getcwd()
os.mkdir("empetrishki")
empetrishki = path + "/empetrishki" #destination dir
print(path)
print(empetrishki)

#recursive collection
for root, dirs, files in os.walk(path, topdown=True, onerror=None, followlinks=True):
    for name in files:
        filePath = Path(name)
        if filePath.suffix.lower() == ".mp3":
            print(filePath)
            os.path.join
            filePath.rename(empetrishki.joinpath(filePath))

我在移动文件的最后一行遇到问题:filePath.rename()shutil.movejoinpath() 都为我工作。也许那是因为我正在尝试更改元组中的元素 - os.walk 的输出

类似的代码适用于os.scandir,但这只会收集当前目录中的文件

如何解决这个问题,谢谢!

【问题讨论】:

    标签: python directory os.walk collect


    【解决方案1】:

    如果你使用 pathlib.Path(name) 并不意味着存在名为 name 的东西。因此,您确实需要小心您拥有完整路径或相对路径,并且您需要确保解决这些问题。特别是我注意到你没有改变你的工作目录并且有这样的一行:

    filePath = Path(name)
    

    这意味着当您沿着目录走时,您的工作目录可能不会改变。您应该从根目录和名称创建路径,解析以便知道完整路径也是一个好主意。

    filePath = Path(root).joinpath(name).resolve()
    

    您也可以将 Path(root) 放在内部循环之外。现在您有了从“/home/”到文件名的绝对路径。因此,您应该能够使用 .rename() 重命名,例如:

    filePath.rename(x.parent.joinpath(newname))
    #Or to another directory
    filePath.rename(other_dir.joinpath(newname))
    

    大家一起:

    from pathlib import os, Path
    
    empetrishki = Path.cwd().joinpath("empetrishki").resolve()
    for root, dirs, files in os.walk(path, topdown=True, onerror=None, followlinks=True):
        root = Path(root).resolve()
        for name in files:
            file = root.joinpath(name)
            if file.suffix.lower() == ".mp3":
                file.rename(empetrishki.joinpath(file.name))
    

    【讨论】:

    • 感谢您的解释!由于最后一行重命名/移动,它没有立即工作。我想这是因为给了一个文件的.joinpath完整的PossixPath,而不仅仅是它的后缀名:file.rename(empetrishki.joinpath(name))
    • 啊,对。我可以解决这个问题。你也可以做 file.name 。 :-)
    【解决方案2】:
    for root, dirs, files in os.walk(path, topdown=True, onerror=None, followlinks=True):
        if root == empetrishki:
            continue  # skip the destination dir
        for name in files:
            basename, extension = os.path.splitext(name)
            if extension.lower() == ".mp3":
                oldpath = os.path.join(root, name)
                newpath = os.path.join(empetrishki, name)
                print(oldpath)
                shutil.move(oldpath, newpath)
    

    这是我的建议。您的代码在当前目录中运行,文件位于路径os.path.join(root, name),您需要为移动函数提供这样的路径。

    此外,我还建议使用os.path.splitext 来提取文件扩展名。更蟒蛇。而且您可能还想跳过扫描目标目录。

    【讨论】:

    • 我强烈建议坚持使用 pathlib 模块而不是 os.path。
    • 感谢您的帮助!我保存了skip the dir 部分
    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 2020-04-11
    • 2012-02-24
    • 1970-01-01
    • 2021-09-18
    • 2010-09-06
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多