【问题标题】:Sort a list of files using Python使用 Python 对文件列表进行排序
【发布时间】:2011-08-25 05:12:18
【问题描述】:

我需要将一个充满 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()

【问题讨论】:

    标签: python sorting pdf-generation


    【解决方案1】:

    pdfList.sort 替换为

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

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

    【讨论】:

      【解决方案2】:

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

      pdfList.sort()
      

      您编写它的方式实际上不会对列表进行排序。我抓住了你的文件名列表,将它们放在一个数组中,并按照你显示的顺序排序。

      【讨论】:

      • 我试过了,但它仍然不能正确排序......它变成了 1、10、100、101 等等......
      【解决方案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)
      

      【讨论】:

      • 我认为这是正确的答案。有人可以举例说明我将如何做到这一点吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2018-07-03
      • 2022-12-21
      • 2018-04-17
      • 1970-01-01
      相关资源
      最近更新 更多