小编SXC*_*C88的帖子

如何在另一个目录下复制文件夹结构?

我有一些与复制文件夹结构有关的问题.实际上,我需要将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)

python directory copy subdirectory

6
推荐指数
2
解决办法
1万
查看次数

python threading.timer在程序运行时间时设置时间限制

我有一些与在Python中设置函数的最大运行时间相关的问题.实际上,我想pdfminer用来将.pdf文件转换为.txt.

问题是,很多时候,某些文件无法解码并且需要很长时间.所以我想设置threading.Timer()为将每个文件的转换时间限制为5秒.另外,我在windows下运行,所以我不能使用这个signal模块.

我成功运行了转换代码pdfminer.convert_pdf_to_txt()(在我的代码中是" c"),但我不确定以下代码中是否threading.Timer()有效.(我认为这不会限制每次处理的时间)

总之,我想:

  1. 将pdf转换为txt

  2. 每次转换的时间限制为5秒,如果超时,则抛出异常并保存空文件

  3. 将所有txt文件保存在同一文件夹下

  4. 如果有任何异常/错误,仍然保存文件但内容为空.

这是当前的代码:

import converter as c
import os
import timeit
import time
import threading
import thread

yourpath = 'D:/hh/'

def iftimesout():
    print("no")

    with open("D:/f/"+g+"&"+t+"&"+name+".txt", mode="w") as newfile:
        newfile.write("")


for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        try:
           timer = threading.Timer(5.0,iftimesout)
           timer.start()
           t=os.path.split(os.path.dirname(os.path.join(root, name)))[1]
           a=str(os.path.split(os.path.dirname(os.path.join(root, name)))[0])
           g=str(a.split("\\")[1])

           with open("D:/f/"+g+"&"+t+"&"+name+".txt", mode="w") as newfile:
                newfile.write(c.convert_pdf_to_txt(os.path.join(root, name)))
                print("yes") …
Run Code Online (Sandbox Code Playgroud)

python multithreading timeout timer

2
推荐指数
1
解决办法
2078
查看次数

标签 统计

python ×2

copy ×1

directory ×1

multithreading ×1

subdirectory ×1

timeout ×1

timer ×1