【问题标题】:how to iterate through files in directory with multiple folders, operate on files, save to different set of folders如何遍历具有多个文件夹的目录中的文件,对文件进行操作,保存到不同的文件夹集
【发布时间】:2019-09-10 02:13:15
【问题描述】:

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

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

【问题讨论】:

  • 您能展示一下您的os.walk 尝试吗?如果你想递归遍历一堆文件夹,那绝对是要走的路。

标签: python os.walk


【解决方案1】:

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

【讨论】:

  • 非常感谢;这真的很有帮助。当然,它运行得非常好。
猜你喜欢
  • 1970-01-01
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2019-05-08
相关资源
最近更新 更多