首页 > 解决方案 > 使用 os.walk 在每个子目录上执行函数 - Python

问题描述

我正在开发一个项目,该项目使用 os.walk 搜索单个 jpg 图像的子目录并将它们编译为 pdf 文档。我需要为 os.walk(搜索目录)的每个子目录创建一个 pdf 文档。我目前正在使用的脚本将在搜索目录中找到的每个 jpg 组合成一个巨大的 pdf。有没有办法使用 os.walk 为 os.walk(search directory) 的每个子目录创建一个 pdf?

这是目录树的示例:

 <SearchDirectory>
   Roll 01
      frames
        001.jpg
        002.jpg
        003.jpg
   Roll 02
      frames
        001.jpg
        002.jpg
        003.jpg
   Roll 03
      frames
        001.jpg
        002.jpg
        003.jpg

这是 abarnert 反馈后更正的脚本:

 import os, sys, img2pdf

 if len(sys.argv) > 1:
     SearchDirectory = sys.argv[1]
     print ("I'm looking for JPGs in ", SearchDirectory)
 else:
     print ("Please tell me the directory to look in")
     sys.exit()

 for root, dirs, files in os.walk(SearchDirectory):
     image_files = []
     for file in files:
         if ((os.path.basename(root)) == "frames") and (file.endswith(".jpg") or file.endswith(".JPG")):
             print("Discovered this jpg: ", os.path.join(root, file))
             image_files.append(os.path.join(root, file))

     if image_files:
         output_file = SearchDirectory + "\\" + (os.path.split(os.path.split(os.path.realpath(root))[0])[1]) + ".pdf"
         print ("Putting all JPGs into ", output_file)
         pdf_bytes = img2pdf.convert(image_files)
         file = open(output_file,"wb")
         file.write(pdf_bytes)
     else:
         print ("Couldn't find any JPGs")

标签: pythonpython-3.xos.walk

解决方案


如果要处理每个子目录的图像文件,则应将处理逻辑放在os.walk循环中。image_files每个循环也应该重新初始化:

import os, sys, img2pdf

if len(sys.argv) > 1:
    SearchDirectory = sys.argv[1]
    print("I'm looking for JPGs in ", SearchDirectory)
else:
    print("Please tell me the directory to look in")
    sys.exit()

for root, dirs, files in os.walk(SearchDirectory):
    image_files = []
    for file in files:
        if ((os.path.basename(root)) == "frames") and (file.endswith(".jpg") or file.endswith(".JPG")):
            print("Discovered this jpg:", os.path.join(root, file))
            image_files.append(os.path.join(root, file))
    if image_files:
        output_file = SearchDirectory + "\\" + (os.path.split(os.path.split(os.path.realpath(root))[0])[1]) + ".pdf"
        print("Putting all JPGs into", output_file)
        pdf_bytes = img2pdf.convert(image_files)
        file = open(output_file, "wb")
        file.write(pdf_bytes)
    else:
        print("Couldn't find any JPGs in", root)

推荐阅读