1

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.

2
  • This SO question should give you some ideas: stackoverflow.com/questions/17057544/… Commented May 3, 2020 at 15:57
  • C:\Users\precious\Desktop\hello.txt >> hello >> rhello >> C:\Users\precious\Desktop\rhello.txt. This is what you want ? Commented May 3, 2020 at 16:12

1 Answer 1

2
import pathlib
p = pathlib.Path(r'C:\Users\precious\Desktop\hello.txt')
newname = pathlib.Path(p.parent, 'r' + p.name)
p.rename(newname)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.