python - 使用 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")
解决方案
如果要处理每个子目录的图像文件,则应将处理逻辑放在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)
推荐阅读
- angular - 即使在组件销毁后订阅服务 observable 也会发出
- javascript - 确定用户是否从手机访问页面最可靠的方法是什么?
- perl - 无法使用 eBay API 更新列表的描述
- c# - 将列表合并为一个列表,其中包含最便宜的列表
- reactjs - react-testing-library: Render prop - 最后一次调用的预期模拟函数:[false] 但它没有被调用
- dialogflow-es - Dialogflow中自动扩展实体的组合
- php - 如何计算文件夹中已存在的文件数
- javascript - 我可以将旧版 html/js 脚本添加到 React 中吗
- reactjs - TS:没有类型的 Redux Actions
- java - 在 Java 中获取文本大小(以字节为单位)的最佳方法是什么?