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

问题描述 投票:0回答:1

我想迭代目录中所有文件夹中的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)

计划为各种操作做这个,所以希望学习一些通用的解决方案。

python os.walk
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.