【问题标题】:How to rename part of a filename represented as string in Python 3 [duplicate]如何重命名在Python 3中表示为字符串的文件名的一部分[重复]
【发布时间】:2017-07-27 13:58:28
【问题描述】:

我想用新名称重命名/替换部分字符串。

我有一个代表文件的字符串,包括它的路径和文件扩展名,如下所示。

source_file = 'images/filename.jpg'

下面显示了我到目前为止所做的尝试。但是,它有效,是否有更好的方法来产生相同的结果?我通过更短的语法和更高效来定义“更好”。

    import uuid

    source_file = 'images/filename.jpg'
    split = source_file.rsplit('/', 1)
    path, filename = split[0], split[1]

    ext = filename.rsplit('.', 1)[1]

    # rebuild
    renamed = path + str(uuid.uuid4()) + ext

【问题讨论】:

  • @Professor_Joykill ,在发布之前我没有考虑过字符串可以使用os.path 函数。但是,是的,OP 可能是重复的,现在 cᴏʟᴅsᴘᴇᴇᴅ 已经明确了这一点。我想奖励积分,因为它对我有帮助,请指教?
  • 无论如何,请随意标记已接受的答案。 :)

标签: python python-3.x


【解决方案1】:

您可以采用pathlib 方法作为查看它并使用新的很棒的模块的另一种方法。

因此,您可以按照自己的方式创建一个 Path 对象:

from pathlib import Path
p = Path('images/full_res/aeb2ffaf-2c4c-4c54-a356-fd0df7764222.jpg')

# get the name without extension
name_without_extension = p.stem
# extension part
ext = p.suffix

p.rename(Path(p.parent, renamed_file + ext))

更多:

p = Path('images/full_res/aeb2ffaf-2c4c-4c54-a356-fd0df7764222.jpg')
p.rename(Path(p.parent, 'new_uuid' + p.suffix))

【讨论】:

    【解决方案2】:
    1. 使用os.path.split 将路径分成头部和尾部。

    2. os.path.splitext在extension上拆分tail,用新的uuid替换tail

    3. 致电os.path.join加入头​​部和新尾部


    In [1006]: head, tail = os.path.split('images/full_res/aeb2ffaf-2c4c-4c54-a356-fd0df7764222.jpg')
    
    In [1008]: tail = str(uuid.uuid4()) + os.path.splitext(tail)[-1]
    
    In [1010]: os.path.join(head, tail)
    Out[1010]: 'images/full_res/a83e5a31-8d30-47d9-b073-d4439e0e4b2f.jpg'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 2020-06-04
      • 2018-12-31
      • 1970-01-01
      相关资源
      最近更新 更多