2011-05-13 67 views
2

我需要将一个装满pdf的文件夹合并到一个文件中。但是,它们必须按照一定的顺序进行组合。文件名的示例是:使用Python对文件列表进行排序

WR_Mapbook__1.pdf 
WR_Mapbook__1a.pdf 
WR_Mapbook__2.pdf 
WR_Mapbook__2a.pdf 
WR_Mapbook__3.pdf 
WR_Mapbook__3a.pdf 
etc... 

它们在Windows资源管理器中排序的方式是我需要将它们添加到单个文件的方式。但是,我的脚本首先添加所有“a”文件,然后添加没有“a”的文件。它为什么这样做?我如何对它进行排序,以便以我想要的方式添加文件?

请参阅下面的代码。谢谢!

from pyPdf import PdfFileWriter, PdfFileReader 
import glob 

outputLoc = "K:\\test\\pdf_output\\" 
output = PdfFileWriter() 


pdfList = glob.glob(r"K:\test\lidar_MB_ALL\*.pdf") 
pdfList.sort 
print pdfList 
for pdf in pdfList: 
    print pdf 
    input1 = PdfFileReader(file(pdf, "rb")) 
    output.addPage(input1.getPage(0)) 
    # finally, write "output" to document-output.pdf 
    outputStream = file(outputLoc + "WR_Imagery_LiDar_Mapbook.pdf", "wb") 
    output.write(outputStream) 
    print ("adding " + pdf) 

outputStream.close() 

回答

7

你需要的是执行"Natural Order String Comparison". 希望有人已经做到了这一点,并分享了它。

编辑:下面是一个暴力的Python例子。

import re 

digits = re.compile(r'(\d+)') 
def tokenize(filename): 
    return tuple(int(token) if match else token 
       for token, match in 
       ((fragment, digits.search(fragment)) 
        for fragment in digits.split(filename))) 

# Now you can sort your PDF file names like so: 
pdfList.sort(key=tokenize) 
+0

我认为这是正确的答案。有人可以提供我如何做到这一点的例子吗? – Justin 2011-05-16 14:17:42

+0

@justin,我已经编辑了答案。 – 2011-05-17 04:30:40

3

通过

pdfList = sorted(pdfList, key = lambda x: x[:-4])

pdfList = sorted(pdfList, key = lambda x: x.rsplit('.', 1)[0])更换pdfList.sort忽略文件扩展名而排序

8

尝试把()pdfList.sort后为:

pdfList.sort() 

你写它的方式不会实际排序列表。我抓住你的文件名列表,将它们粘在一个数组中,然后按你显示的顺序排序。

+1

我试过了,但是它仍然没有正确排序......它变成了1,10,100,101等...... – Justin 2011-05-16 14:19:43