简体   繁体   English

使用python在特定条件下向PDF文件名添加文本

[英]Adding text to PDF file name under specific conditions using python

I'm trying to edit file names of pdfs under specific conditions.我正在尝试在特定条件下编辑 pdf 的文件名。

The names have been generated according to numbers entered into a database (non changeable) and are being referenced in another script, however, some names are followed by decimal places (543435.00, or 53838.01, and some are not (548538, 585040) I need to add the .00 to those which dont have decimal places.这些名称是根据输入到数据库中的数字(不可更改)生成的,并在另一个脚本中被引用,但是,有些名称后跟小数位(543435.00 或 53838.01,有些不是(548538、585040)我需要将 .00 添加到没有小数位的那些。

The full pdf names are presented in this format 387359_21.pdf or 33982.00_39.pdf完整的 pdf 名称以这种格式显示 387359_21.pdf 或 33982.00_39.pdf

Is there a way to do this for a selection of files?有没有办法为选择的文件做到这一点?

Try using the os and regular expressions re library in the following way:尝试通过以下方式使用os和正则表达式re库:

import os
import re

# Split file name to append '.00' before .pdf extension
def append_suffix(filename):
    name, ext = os.path.splitext(filename)
    return '{name}_{suffix}{extension}'.format(name=name, suffix='.00', ext=ext)

# Regular expression to match if filename has two digits after decimal point
regex = re.compile('[0-9]*\.[0-9]{2}')

# Loop through filenames in directory append suffix if filename doesn't match regex
for filename in os.listdir('.'):
    if re.search(regex, filename) is None:
        os.rename(filename, append_suffix(filename))

You can see how the above regular expression works here: https://regex101.com/r/aW3pR4/82您可以在此处查看上述正则表达式的工作原理: https : //regex101.com/r/aW3pR4/82

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM