SXC*_*C88 6 python directory copy subdirectory
我有一些与复制文件夹结构有关的问题.实际上,我需要将pdf文件转换为文本文件.因此我在导入pdf的地方有这样的文件夹结构:
D:/f/subfolder1/subfolder2/a.pdf
Run Code Online (Sandbox Code Playgroud)
我想在" D:/g/subfolder1/subfolder2/" 下创建确切的文件夹结构,但没有pdf文件,因为我需要在这个地方放置转换后的文本文件.所以在转换功能之后它给了我
D:/g/subfolder1/subfolder2/a.txt
Run Code Online (Sandbox Code Playgroud)
而且我想添加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)))
Run Code Online (Sandbox Code Playgroud)
lin*_*usg 13
对我来说,以下工作正常:
迭代现有文件夹
根据现有文件夹构建新文件夹的结构
码:
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!")
Run Code Online (Sandbox Code Playgroud)
文档:
使用shutil.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)
Run Code Online (Sandbox Code Playgroud)
在调用此函数之前,您要创建的目录不应该存在.您可以添加一个检查.
| 归档时间: |
|
| 查看次数: |
10452 次 |
| 最近记录: |