用于压缩Windows 7上目录中所有pdf文件的Python脚本

时间:2014-12-24 05:23:44

标签: python pdf python-3.x compression ghostscript

在代码示例here之后,我有下面的代码,它应该使用Ghostscript压缩目录中的文件。代码压缩文件,但是当我打开文件时,我根本看不到任何内容。我只希望压缩文件。我不希望删除内容。

from __future__ import print_function
import os
import subprocess

for root, dirs, files in os.walk("C:\comp"):
    for file in files:
        if file.endswith(".pdf"):
            filename = os.path.join(root, file)
            print (filename)
            arg1= '-sOutputFile=' + file
            p = subprocess.Popen(['C:/Program Files/gs/gs9.15/bin/gswin64c.exe',
                                  '-sDEVICE=pdfwrite', 
                                  '-dCompatibilityLevel=1.4', 
                                  '-dPDFSETTINGS=/screen', '-dNOPAUSE', 
                                  '-dBATCH', '-dQUIET', str(arg1), filename], 
                                 stdout=subprocess.PIPE)
            print (p.communicate())

1 个答案:

答案 0 :(得分:0)

我在@KenS建议给输出文件一个不同的名字后解决了这个问题,这很有效。

from __future__ import print_function
import os
import subprocess

for root, dirs, files in os.walk("C:\comp"):
    for file in files:
        if file.endswith(".pdf"):
            filename = os.path.join(root, file)
            print (filename)
            arg1= '-sOutputFile=' + "c" +  file #added a c to the filename
            p = subprocess.Popen(['C:/Program Files/gs/gs9.15/bin/gswin64c.exe',
                                  '-sDEVICE=pdfwrite', 
                                  '-dCompatibilityLevel=1.4', 
                                  '-dPDFSETTINGS=/screen', '-dNOPAUSE', 
                                  '-dBATCH', '-dQUIET', str(arg1), filename], 
                                 stdout=subprocess.PIPE)
            print (p.communicate())