如何在另一个目录下复制文件夹结构? [英] How to copy folder structure under another directory?
问题描述
我有一些与复制文件夹结构有关的问题。实际上,我需要将pdf文件转换为文本文件。因此,我在导入pdf的位置具有这样的文件夹结构:
I have some questions related to copying a folder structure. In fact, I need to do a conversion of pdf files to text files. Hence I have such a folder structure for the place where I import the pdf:
D:/f/subfolder1/subfolder2/a.pdf
我想在 D下创建确切的文件夹结构:/ g / subfolder1 / subfolder2 /
,但没有pdf文件,因为我需要在此处放置转换后的文本文件。因此,在转换函数之后
And I would like to create the exact folder structure under "D:/g/subfolder1/subfolder2/
" but without the pdf file since I need to put at this place the converted text file. So after the conversion function it gives me
D:/g/subfolder1/subfolder2/a.txt
我也想添加if函数以确保在 D:/ g /
创建之前,不存在相同的文件夹结构。
And also I would like to add if function to make sure that under "D:/g/
" the same folder structure does not exist before creating.
这是我当前的代码。那么如何在没有文件的情况下创建相同的文件夹结构?
Here is my current code. So how can I create the same folder structure without the file?
谢谢!
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)))
推荐答案
对我来说,以下工作正常:
For me the following works fine:
-
对现有文件夹进行迭代
Iterate over existing folders
基于现有文件夹构建新文件夹的结构
Build the structure for the new folders based on existing ones
代码:
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!")
文档:
os.walk
os.mkdir
os.path.isdir
这篇关于如何在另一个目录下复制文件夹结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!