【问题标题】:Using os.walk to execute function on each subdirectory - Python使用 os.walk 在每个子目录上执行函数 - Python
【发布时间】:2018-07-26 22:13:42
【问题描述】:

我正在开发一个项目,该项目使用 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")

【问题讨论】:

  • 只需将image_files = [] 和整个if image_files: 块移动到外部for … in os.walk…: 循环内。您需要进行的唯一其他更改是从步行中的当前位置创建output_file。就是这样。
  • 这成功了。非常感谢您的帮助。

标签: python python-3.x os.walk


【解决方案1】:

如果您想处理每个子目录的图像文件,那么您应该将处理逻辑放在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)

【讨论】:

  • 感谢您的回复。我相信这种方法可以将每个单独的 jpg 转换为 pdf。我正在尝试将每个 jpg 组合成每个子目录的 pdf。
  • @RBanks82 我明白了。在那种情况下,阿巴纳特提到的确实很好。
猜你喜欢
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 2023-01-09
  • 1970-01-01
  • 2013-06-01
相关资源
最近更新 更多