4/7/2024 0 Comments Change file extension![]() ![]() Using functools.reduce and pathlib's with_suffix: import pathlib Using pathlibs with_name (best solution, in my opinion): import pathlib Print(p.with_name(p.stem).with_suffix('.jpg')) Replace Up to Two Extensions import pathlib Using Path Objects Replace Up to One Extension import pathlib Here are several ways to accomplish extension replacement. I'm also concerned that some answers here don't handle a. That said, I'm surprised nobody has mentioned pathlib's with_name. The best way to do this will depend on your version of python and how many extensions you need to handle. Return Path(str(p).replace(extensions, new_ext))Īssert replace_ext(p, new_ext) = Path('/path/to/myfile.jpg')Īssert replace_ext(str(p), new_ext) = Path('/path/to/myfile.jpg')Īssert replace_ext(p) = Path('/path/to/myfile')īest way to replace all extensions, in my opinion, is the following. Wrapping it all up in a function from pathlib import Pathĭef replace_ext(path: PathLike, new_ext: str = "") -> Path:Įxtensions = "".join(Path(path).suffixes) If you also want a pathlib object output then you can obviously wrap the line in Path() > Path(str(p).replace("".join(p.suffixes), "")) Replace extensions > p = Path("/path/to/") In the case where you have multiple extensions using pathlib and str.replace works a treat: Remove/strip extensions > from pathlib import Path
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |