2011-05-13 69 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