我有一些与复制文件夹结构相关的问题。事实上,我需要将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)))
对我来说,以下工作正常:
迭代现有文件夹
基于现有文件夹构建新文件夹的结构
- 检查新的文件夹结构是否不存在
- 如果是,则创建新文件夹没有文件
Code:
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 https://docs.python.org/2/library/os.html#os.walk
- os.mkdir https://docs.python.org/2/library/os.html#os.mkdir
- os.path.isdir https://docs.python.org/2/library/os.path.html#os.path.isdir
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)