【问题标题】:Rename duplicate pdf name by increasing counter通过增加计数器重命名重复的 pdf 名称
【发布时间】:2021-06-12 11:10:01
【问题描述】:

所以我写了一些东西来从pdf中提取某些字符串(受益人)并根据字符串重命名文件,但问题是如果有重复,有没有办法在名字后面添加一个+1计数器?

我的低效代码如下,感谢任何帮助!:

for filename in os.listdir(input_dir):
    if filename.endswith('.pdf'):
        input_path = os.path.join(input_dir, filename)


pdf_array = (glob.glob(input_dir + '*.pdf'))

for current_pdf in pdf_array:
    with pdfplumber.open(current_pdf) as pdf:
        page = pdf.pages[0]
        text = page.extract_text()

        keyword = text.split('\n')[2]

        try:

            if 'attention' in keyword:

                pdf_to_att = text.split('\n')[2]
                start_to_att = 'For the attention of: '
                to_att = pdf_to_att.removeprefix(start_to_att)
                pdf.close()
                result = to_att
                os.rename(current_pdf, result + '.pdf')
                
            else:

                pdf_to_ben = text.split('\n')[1]
                start_to_ben = 'Beneficiary Name : '
                end_to_ben = pdf_to_ben.rsplit(' ', 1)[1]
                to_ben = pdf_to_ben.removeprefix(start_to_ben).removesuffix(end_to_ben).rstrip()
                pdf.close()
                result = to_ben
                os.rename(current_pdf, result + '.pdf')
                
        except Exception:
            pass

messagebox.showinfo("A Title", "Done!")

编辑:所需的输出应该是

AAA.pdf

AAA_2.pdf

BBB.pdf

CCC.pdf

CCC_2.pdf

【问题讨论】:

标签: python rename


【解决方案1】:

我会使用字典来记录每个文件名的出现次数。

dict.get() 如果 key 在字典中,则返回 key 的值,否则返回 default。如果没有给出default,则默认为None

pdf_name_count = {}

for current_pdf in pdf_array:
    with pdfplumber.open(current_pdf) as pdf:
        page = pdf.pages[0]
        text = page.extract_text()

        keyword = text.split('\n')[2]

        try:

            if 'attention' in keyword:
                ...
                result = to_att
                
            else:
                ...
                result = to_ben

            filename_count = pdf_name_count.get(result, 0)
            if filename_count >= 1:
                filename = f'{result}_{filename_count+1}.pdf'
            else:
                filename = result + '.pdf'
            os.rename(current_pdf, filename)
            # increase the name occurrence by 1
            pdf_name_count[result] = filename_count + 1

        except Exception:
            pass

【讨论】:

    【解决方案2】:

    os.path.isfile可以成为你的伴侣,满足你的需求。

    import os
    
    
    def get_new_name(result):
        file_name = result + '{}.pdf'
        file_number = 0
        if os.path.isfile(file_name.format('')):  # AAA.pdf
            file_number = 2
        while os.path.isfile(file_name.format('_{}'.format(file_number))):
            file_number += 1
    
        if file_number:
            pdf_name = file_name.format('_{}'.format(file_number))
        else:
            pdf_name = file_name.format('')
    
        return pdf_name
    

    my screenshot

    我更新了你的输出格式的代码,它可以工作。

    【讨论】:

    • 我尝试在 "result = to_att" 之后插入它,但它不起作用
    • 我更新了代码并测试了,你可以试试。
    • 嗨,我很感谢你的回答,我选择了另一个,因为我对函数 xD 太菜鸟了
    • 你选择的答案我看了,比较清楚。
    【解决方案3】:

    你想要的是为文件名构建一个包含计数器的字符串, 我们称之为cnt。 Python 具有用于这个确切目的的 f-string 语法,它 允许您将变量插入到字符串中。

    for 循环之前初始化您的计数器:

    cnt = 0
    

    替换

    os.rename(current_pdf, result + '.pdf')
    

    os.rename(current_pdf, f'{result}_{cnt}.pdf')
    cnt += 1
    

    开头引号前的f 引入了 f 字符串和花括号 {} 让您包含任何 python 表达式,在您的情况下,我们只需替换 resultcnt 两个变量的值。然后我们增加计数器, 当然。

    【讨论】:

    • 它通过在每个文件上添加 _0, _1.... 来工作,但我只想在有任何重复时添加计数器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多