Naming of file while saving with extension
Asked Answered
B

1

-2

How can I save a file with the name as: oldname+"_new"+extension in an elegant way?

I currently do:

ext = os.path.splitext(file)[1]
output_file = (root+'/'+ os.path.splitext(file)[0]+"_new"+ext)
#or output_file = (os.path.join(root, os.path.splitext(file)[0])+'_new'+ext)

with open(output_file, 'w', encoding='utf-8') as file:
      file.write(text)

(with the help of Python: how to retain the file extension when renaming files with os? , but not duplicate)

-- I use Python 3.12.2

Baalman answered 15/4 at 9:35 Comment(3)
What version of python are you using? If at least 3.6, f-strings make it much more readable.Gulosity
You're making two calls to the same splittext function so at the very least can save those to variables filename, ext = splittext(.. but these are all trivial changesLadew
added version (3.12.x) to question @GulosityBaalman
B
2

pathlib.Path is preferred in modern code for a more OO approach.

For example:

from pathlib import Path

def makenew(filename: Path, new: str = "_new") -> Path:
    return filename.parent / (filename.stem + new + filename.suffix)

print(makenew(Path("/Users/SIGHUP/foo.txt")))

Output:

/Users/SIGHUP/foo_new.txt
Bonin answered 15/4 at 11:9 Comment(1)
filename.parent / ... is already a Path object; you don't need to explicitly call Path to create the return value.Squinch

© 2022 - 2024 — McMap. All rights reserved.