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

2024-05-01 13:17:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件函数importtxt文件夹forpdfos
3条回答

使用shuil.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!")

文件:

相关问题 更多 >