0

I want to rename/replace part of the string with a new name.

I have a string that represents a file including its path and file extension as shown below.

source_file = 'images/filename.jpg'

Below shows what I have tried so far. It works, however, is there a better way to produce the same outcome? I define 'better' by, shorter syntax and more efficient.

    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
Prometheus
  • 32,405
  • 54
  • 166
  • 302
  • @Professor_Joykill , I had not considered that the string could use `os.path` function until posted. However, yes, OP could be a duplicate now this has been made clear by cᴏʟᴅsᴘᴇᴇᴅ. I would like like to award points tho, as it helped me, please advise? – Prometheus Jul 27 '17 at 14:10
  • Feel free to mark an answer accepted regardless. :) – cs95 Jul 27 '17 at 14:29

2 Answers2

7

You can take the pathlib approach just as an alternative way to look at it and making use of a new awesome module.

So, you can take your path and create a Path object out of it:

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))

More shortly:

p = Path('images/full_res/aeb2ffaf-2c4c-4c54-a356-fd0df7764222.jpg')
p.rename(Path(p.parent, 'new_uuid' + p.suffix))
LKho
  • 47
  • 2
  • 10
idjaw
  • 25,487
  • 7
  • 64
  • 83
2
  1. Use os.path.split to split your path into head and tail.

  2. os.path.splitext splits the tail on extension, replace the tail with the new uuid

  3. Call os.path.join to join head and new tail


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'
cs95
  • 379,657
  • 97
  • 704
  • 746