使用Python对文件列表排序

2024-09-26 17:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将一个文件夹中的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()

Tags: 文件importoutputpdf排序方式wrglob
3条回答

你需要的是实现"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)

尝试在pdfList.sort之后放置(),如下所示:

pdfList.sort()

你写这封信的方式实际上并不能对名单进行排序。我抓起你的文件名列表,把它们放在一个数组中,然后按照你显示的顺序进行排序。

替换为pdfList.sort

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

或者

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

相关问题 更多 >

    热门问题