使用Python对文件列表进行排序

3

我需要将一个文件夹中的PDF文件合并成一个文件,但是它们必须按照特定的顺序进行合并。文件名的示例如下:

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()
3个回答

11
你需要实现"自然排序字符串比较"。希望已经有人做过并分享了它。 编辑: 这里是一个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)

我认为这是正确的答案。有人能提供一个示例,说明我该如何做吗? - Justin

10
尝试在pdfList.sort后放置(),例如:
pdfList.sort()

按照你目前的写法,它实际上不会对列表进行排序。我将你的文件名列表放到了一个数组中,它们按照你展示的顺序排序。


1
我尝试了这个,但它仍然无法正确排序... 它会变成1、10、100、101等等... - Justin

3

pdfList.sort替换为

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

或者

pdfList = sorted(pdfList, key = lambda x: x.rsplit('.', 1)[0])以忽略文件扩展名进行排序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接