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

How to copy folder structure under another directory?

我有一些关于复制文件夹结构的问题。事实上,我需要将 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)))

使用 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

对您的代码进行细微调整以跳过 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)))

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

  • 迭代现有文件夹

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

  • 检查,如果新的文件夹结构不存在
  • 如果是,创建新文件夹不带文件

代码:

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!")

文档: