python复制文件夹结构在另一个目录下 [英] python 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 / / code>在创建之前,相同的文件夹结构不存在。
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
这篇关于python复制文件夹结构在另一个目录下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!