【发布时间】:2018-11-05 18:40:50
【问题描述】:
目前我正在开发一个项目,该项目将占用许多文件夹并将每个文件夹的内容合并到一个 pdf 中。这意味着每个文件夹将输出一个 pdf。我能够弄清楚如何使用 ReportLab 将我正在使用的文件合并为单个 pdf。现在我需要让它遍历每个文件夹并创建一个 pdf。到目前为止,我可以使用 os.walk 来运行我的测试目录,但它不会运行 pdf 脚本。
import glob
import os
import re
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, PageBreak
from reportlab.lib.units import inch
list_of_files = ["C:\\foo_1", "C:\\foo_2"]
os.chdir("C:\\foo")
for root, dirs, files in os.walk(".", topdown = False):
for name in files:
print(os.path.join(root, name)) #used to see where os.walk is working
def sorted_nicely( l ):
"""
http://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python
Sort the given iterable in the way that humans expect.
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
def collect_issue(fname):
if not fname.endswith(".pdf"):
fname += ".pdf"
doc = SimpleDocTemplate(fname,pagesize=letter,
rightMargin=0,leftMargin=0,
topMargin=0,bottomMargin=0)
width = 7.5*inch
height = 9.5*inch
picture_file_names = sorted_nicely(glob.glob("*.jp2"))
contents = []
for pic_fname in picture_file_names:
im = Image(pic_fname, width=width, height=height)
contents.append(im)
contents.append(PageBreak())
doc.build(contents)
if __name__ == "__main__":
collect_issue("test")
我正在寻找使用 os.walk 的帮助,以便让 pdf 脚本通过我需要的许多文件夹运行。我不完全确定究竟是什么导致它也不起作用。作为参考,此代码中的许多代码都基于this script。
【问题讨论】:
-
您的代码缩进已关闭 - 您错过了
"这就是为什么您的所有代码都是红色的。 .if __name__ == ...应该是 0 缩进 lvl ,你的功能可能也是如此。请修复。- -
@PatrickArtner 感谢您的编辑和反馈。我很尴尬我错过了
",在本地我有我的实际文件位置,这个问题不存在。我在本地编辑了缩进级别,不幸的是它没有使它工作。 Idle 还会在print(os.path.join(...))之后强制缩进,所以这就是缩进与上面一样的原因。 -
那我们就帮不了你了——python的缩进对于形成执行块很重要。尝试复制 您的来源 ,将它们粘贴到问题中,选择它们并按 Ctrl+k 格式化为代码
-
@PatrickArtner 代码的格式就像我在本地没有原始目录路径一样。
标签: python python-3.x pdf reportlab os.walk