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
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
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?
Thank you!
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)))
If root string is unique this is easily done using re.sub replacement, and os.walk otherwise you can use slicing on the path string and os.join
For me the following works fine:
Iterate over existing folders
Build the structure for the new folders based on existing ones
Code:
Documentation:
os.walk
os.mkdir
os.path.isdir
A minor tweak to your code for skipping
pdf
files:How about using shutil.copytree()?
The directory you want to create should not exist before calling this function. You can add a check for that.
Taken from shutil.copytree without files