【发布时间】: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