0

我正在尝试使用 Imagemagick 和 python 将 pdf 转换为图像,下面是我的代码

以下文件将 pdf 文件作为命令行输入并转换为图像

转换.py

from subprocess import check_call, CalledProcessError
from os.path import isfile

filename = sys.argv[1]

try:
    if isfile(filename):
        check_call(["convert", "-density", "150", "-trim",
                    filename, "-quality", "100", "-scene", "1", 'hello.jpg'])
except (OSError, CalledProcessError, TypeError) as e:
    print "-----{0}-----".format(e)

上面的代码工作正常,运行文件后,我的目录结构和结果文件是

codes
     convert.py
     example.pdf
     hello.jpg

但我想要的只是在一个文件夹中创建生成的图像(jpg)文件,其 pdf 文件的名称如下所示

codes
     convert.py
     example.pdf
     example/
            hello.jpg

所以任何人都可以让我知道如何使用if not exists上面的pdf名称动态创建一个目录并创建一个上面的jpg文件

4

1 回答 1

1

用于os.path.splitext去除文件扩展名。像这样的东西:

if isfile(filename):
    dirname = os.path.splitext(filename)[0]
    if not os.path.isdir(dirname):
        os.mkdir(dirname)
    outfile = os.path.join(dirname, "hello.jpg")
    check_call(["convert", "-density", "150", "-trim",
                filename, "-quality", "100", "-scene", "1", outfile])

编辑:

要将新目录放在当前工作目录而不是输入文件的父目录中,请使用os.path.basename()and os.getcwd()

dir_base = os.path.basename(os.path.splitext(filename)[0])
dirname = os.path.join(os.getcwd(), dir_base)
于 2013-07-12T12:50:29.697 回答