代码之家  ›  专栏  ›  技术社区  ›  user026

os.makedirs正在创建一个文件名为的新文件夹

  •  0
  • user026  · 技术社区  · 2 年前

    如果一个文件不包含名为“过时”的子字符串,我会尝试将所有文件夹和文件从一个路径复制到另一个路径。这是我的代码:

    import os
    import shutil
    
    rootdir = "C:/Old"     
    new_rootdir = "C:/New/"
    
    for root, dirs, files in os.walk(rootdir):
        for filename in files:
            if not "obsolete" in filename:
                source = root + "\\" + filename
                extra_paths = source.split("\\")[1:]    # strings to be merged to the new destination
                destination = new_rootdir + "/".join(extra_paths)
            
                if not os.path.exists(destination):
                    os.makedirs(destination)  # Create the destination directory if it doesn't exist
            
                if os.path.isdir(source):
                    for root, dirs, files in os.walk(source):
                        for directory in dirs:
                            source_path = os.path.join(root, directory)
                            destination_path = os.path.join(destination, os.path.relpath(source_path, source))
                            if not os.path.exists(destination_path):
                                os.makedirs(destination_path)
                        for file in files:
                            source_path = os.path.join(root, file)
                            destination_path = os.path.join(destination, os.path.relpath(source_path, source))
                            shutil.copy2(source_path, destination_path)
                else:
                    shutil.copy2(source, destination) 
    

    脚本可以工作,但它为每个文件创建一个新的文件夹,上面有它的名称 C:/Old/Documents/example.txt 它正在创造一条新的道路 C:/New/Documents/example.txt/example.txt 应该是 C:/New/Documents/example.txt

    如何修复此问题,使脚本不会创建具有文件名的文件夹?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Barmar    2 年前

    extra_paths 包括文件名。当您将其连接到 destination ,您正在使用目标文件的名称创建一个目录。然后稍后将文件名附加到该文件中。

    请改用此选项:

                extra_paths = root.split("\\")[1:]    # strings to be merged to the new destination