gpt4 book ai didi

python - 根据文件名循环和匹配文件并追加的脚本

转载 作者:行者123 更新时间:2023-11-28 16:58:18 24 4
gpt4 key购买 nike

我有一个包含许多文件的目录,这些文件的名称如下:

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_<today's date>.pdf' .即 1234_combined_051719.pdf

而且如果有一个数字文件只有第 1 部分或其他文件,它不会合并 —即如果有 9999_part1.pdf , 但没有 9999.pdf ,那么 '9999_combined_<today's date>.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')

关于python - 根据文件名循环和匹配文件并追加的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56192546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com