Spider Wings
Spider Wings

Reputation: 81

What is the best way to modify the file name from a file path in python?

I would like to add a letter at the start of a file name in a file path.

For example change this file path-: C:\Users\precious\Desktop\hello.txt

To this-: C:\Users\precious\Desktop\rhello.txt

In other words, is there a way I can input a file path such as-: C:\Users\precious\Desktop\hello.txt

And the program will remove the extension and path from the string and consolidate it to-:

hello

Then add a letter at the start of that string and make it-:

rhello

Then puts the edited file name back into the file path-:

C:\Users\precious\Desktop\rhello.txt

I have already figured out the first step (consolidating the file name from the path and extension) by using this code-:

file_name = Path(fp).stem

But I still haven't figured out how to take the modified name and put it back into the file path. My goal is to rename the file to a changed file name using os.rename()

The method I am using to do this probably isn't the best, so you can suggest a better way of changing the file name or help me to continue using my method of doing the same.

I am using windows and python 3.

Upvotes: 1

Views: 522

Answers (1)

Błotosmętek
Błotosmętek

Reputation: 12927

import pathlib
p = pathlib.Path(r'C:\Users\precious\Desktop\hello.txt')
newname = pathlib.Path(p.parent, 'r' + p.name)
p.rename(newname)

Upvotes: 2

Related Questions