如何遍历具有多个文件夹的目录中的文件,如何操作文件,保存到不同的文件夹集

时间:2019-04-19 21:30:29

标签: python os.walk

我想遍历目录中所有文件夹中的pdf文件,对这些文件进行操作(提取文本,保存为.txt),然后将所有txt保存到名称相同但位于不同目录中的另一组文件夹中。该功能按预期执行,但不与子文件夹一起执行。我知道这里有os.walk,但是对于如何在这里使用它感到不安。如果我的所有文件都没有子文件夹,则此功能有效;它写入所需的目录。但是我需要遍历这些文件夹,然后保存到其他目录中的那些文件夹中。

在一个目录中找到文件,对其进行操作,然后保存到另一个目录。尝试os.walk,但未成功合并文件夹结构。

文件夹结构基本上是path / folder1 ... folderN

具有30K +文件,因此要保留在文件夹系统中。

def convertall(pdfDir, txtDir):
    if pdfDir == "": pdfDir = os.walk(path) + "\\" 
    for pdf in os.listdir(pdfDir):     --- tried os.walk here too; 
        fileExtension = pdf.split(".")[-1]
        if fileExtension == "pdf":
            pdfFilename = pdfDir + pdf 
            text = convert(pdfFilename)
            textFilename = txtDir + pdf + ".txt"
            textFile = open(textFilename, "w") 
            textFile.write(text)     

pdfDir = pdfpath
txtDir = txtpath   
convertall(pdfDir)

计划针对各种操作执行此操作,因此希望了解一些常规解决方案。

1 个答案:

答案 0 :(得分:0)

os.walk调用的

topdown=True(this_directory_path, directories_in_this_directory, files_in_this_directory)的格式在每次迭代中返回一个元组。元组的第二个和第三个元素是列表,这意味着您也必须遍历它们。因此,您可以像这样遍历目录结构:


import os


def create_my_new_path(old_root)
    # This gives us everything after /home/user/PDFs, e.g. folderN
    relative_path = os.path.relpath(old_root, "/home/user/PDFs")
    # This returns "/home/user/TXTs/folderN"
    return os.path.join("/home/user/TXTs", relative_path)

for root, directories, files in os.walk("/home/user/PDFs", topdown=True):
    for pdf_filename in files:
        # Use .lower() for the comparison in case there are files that end in ".PDF"
        if pdf_filename[-4:].lower() == ".pdf":
            # the variable `root` may not contain the absolute path
            # depending on what you passed to os.walk, so you might
            # want to use os.path.abspath(root) before passing it 
            # to the path builder
            txt_save_dir = create_my_new_path(root)
            txt_filename = "".join(old_filename[:-4], ".txt")
            result = parse_PDF(os.path.join(root, filename))
            with open(os.path.join(txt_save_dir, txt_filename), "w") as f:
                f.write(result)
    for directory in directories:
        # If you wanted to do something with the subfolders too, you could do it here
        continue

我希望这个示例足够容易理解,以便您可以根据需要进行调整。

一些提示:

  1. 建议使用os.path.join来创建文件路径而不是串联,因为如果丢失,它将自动添加操作系统的适当分隔符。如果忘记确保文件夹和文件分开,则会将其写入错误的位置。
  2. with open(path, mode) as myfile:是打开文件的好方法,因为即使抛出异常,它也会在with子句的结尾自动为您关闭文件。这就是官方python教程建议您立即打开文件的方式。 https://docs.python.org/3.7/tutorial/inputoutput.html#reading-and-writing-files

所有os.path操作:https://docs.python.org/3/library/os.path.html

os.walk的用法可以在这里找到:https://docs.python.org/3/library/os.html

相关问题