python 文件名匹配_python-基于文件名和追加来循环和匹配文件的脚本

我有一个目录,其中包含许多文件,它们的名称如下:

1234_part1.pdf

1234.pdf

5432_part1.pdf

5432.pdf

2323_part1.pdf

2323.pdf

etc.

我正在尝试合并文件的第一个数字部分相同的pdf.

我有一次可以执行此操作的代码,但是当目录中有500个以上的文件时,我不确定如何遍历,这是到目前为止的内容:

from PyPDF2 import PdfFileMerger, PdfFileReader

merger = PdfFileMerger()

merger.append(PdfFileReader(file('c:/example/1234_part1.pdf', 'rb')))

merger.append(PdfFileReader(file('c:/example/1234.pdf', 'rb')))

merger.write("c:/example/ouput/1234_combined.pdf")

理想地,输出文件将是“ xxxx_combined_ .pdf”.

即1234_combined_051719.pdf

而且,如果有一个数字文件仅包含第1部分或其他文件,则它不会合并-

即,如果有9999_part1.pdf,但没有9999.pdf,则对于“ 9999_combined_ .pdf”将没有输出.

解决方法:

尝试使用os.listdir()获取目录中的所有文件,然后在字符串(文件名)末尾使用.split()来隔离pdf文件编号.然后在创建的文件列表中查找该数字模式.

import os

from PyPDF2 import PdfFileMerger, PdfFileReader

dir = 'my/dir/of/pdfs/'

file_list = os.listdir(dir)

num_list = []

for fname in file_list:

if '_' in fname: # if the filename has an underscore in it

file_num = fname.split('_')[0] # get's first element in list of splits

else:

file_num = fname.split('.')[0]

if file_num not in num_list:

num_list.append(file_num)

# now you have a list of all of your file numbers you can grab all files

# in the file_list containing that number

for num in num_list:

pdf_parts = [x for x in file_list if num in x] # grabs all files with that number

if len(pdf_parts < 2): # if there is only one pdf with that num ...

continue # skip it!

# your pdf append operation here for each item in the pdf_parts list.

# something like this maybe ...

merger = PdfFileMerger()

# sorts list by filename length in decending order so that

# '_part' files come first

sorted_pdf_parts = pdf_parts.sort(key=len, reverse=True)

for part in sorted_pdf_parts:

merger.append(PdfFileReader(file(dir + part, 'rb')))

merger.write('out/dir/' + num + '_combined.pdf')

标签:pypdf2,python

来源: https://codeday.me/bug/20191210/2104628.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值