如何在另一个目录下复制文件夹结构?

时间:2016-11-27 11:33:37

标签: python directory copy subdirectory

我有一些与复制文件夹结构有关的问题。实际上,我需要将pdf文件转换为文本文件。因此,我在导入pdf的地方有这样的文件夹结构:

D:/f/subfolder1/subfolder2/a.pdf 

我想在“D:/g/subfolder1/subfolder2/”下创建确切的文件夹结构,但没有pdf文件,因为我需要在此处放置转换后的文本文件。所以在转换函数之后它给了我

D:/g/subfolder1/subfolder2/a.txt

而且我想添加if函数以确保在“D:/g/”下创建之前不存在相同的文件夹结构。

这是我目前的代码。那么如何在没有文件的情况下创建相同的文件夹结构呢?

谢谢!

import converter as c
import os
inputpath = 'D:/f/'
outputpath = 'D:/g/'

for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
      with open("D:/g/"+ ,mode="w") as newfile:
          newfile.write(c.convert_pdf_to_txt(os.path.join(root, name)))

4 个答案:

答案 0 :(得分:9)

对我来说,以下工作正常:

  • 迭代现有文件夹

  • 根据现有文件夹构建新文件夹的结构

  • 检查新文件夹结构是否不存在
  • 如果是,请创建新文件夹 without files

代码:

import os

inputpath = 'D:/f/'
outputpath = 'D:/g/'

for dirpath, dirnames, filenames in os.walk(inputpath):
    structure = os.path.join(outputpath, dirpath[len(inputpath):])
    if not os.path.isdir(structure):
        os.mkdir(structure)
    else:
        print("Folder does already exits!")

文档:

答案 1 :(得分:7)

如何使用shutil.copytree()?

import shutil
def ig_f(dir, files):
    return [f for f in files if os.path.isfile(os.path.join(dir, f))]

shutil.copytree(inputpath, outputpath, ignore=ig_f)

在调用此函数之前,您不想存在要创建的目录。您可以为此添加一个检查。

取自shutil.copytree without files

答案 2 :(得分:1)

对您的代码进行小调整以跳过pdf个文件:

for root, dirs, files in os.walk('.', topdown=False):
    for name in files:
        if name.find(".pdf") >=0: continue
        with open("D:/g/"+ ,mode="w") as newfile:
            newfile.write(c.convert_pdf_to_txt(os.path.join(root, name)))

答案 3 :(得分:0)

如果根字符串是唯一的,可以使用 re.sub 替换和 os.walk 轻松完成,否则您可以在路径字符串和 os上使用切片.join

import re
import os
from os import join

def _clone_dirs(self, root, new_root):
    """Walk through root folders and copy to new root"""
    for root_path, _, files in os.walk(root):
        new_folder = re.sub(string=root_path, pattern=root, repl=new_root)
        os.mkdir(new_folder)

def _clone_dirs2(self, root, new_root):
    """Walk through root folders and copy to new root"""
    root_len = len(root)+1
    for root_path, _, _ in os.walk(root):
        new_folder = path.join(new_root, root_path[root_len:])
        os.mkdir(new_folder)