Iakovos Belonias
Iakovos Belonias

Reputation: 1373

I have a string that contains the path to a file, how to change the path

I use google clould storage api. I get the filename like this 'pdf/randomPdf.pdf'

I use

new_filename = Path(file_name).stem + ".txt"

I do this so I can change the name of the extension to .txt

Now I want to change the 'pdf/...' to 'text/...'

How I can do it without split?

Upvotes: 0

Views: 102

Answers (3)

John Gordon
John Gordon

Reputation: 33359

Use the string built-in method replace().

newFilename = filename.replace('pdf/', 'text/').replace('.pdf', '.txt')

Upvotes: 0

Abhineet Gupta
Abhineet Gupta

Reputation: 629

These answers 1 and 2 seem relevant to your question -

You can use os.path.splitext(filename) to extract everything but file extension - pdf/pdfFile in your case.

You can use os.path.dirname(filename) to extract the head - pdf in your case.

You can use os.path.basename(filename) to extract the tail - pdfFile.pdf in your case.

Upvotes: 3

Mike Yue
Mike Yue

Reputation: 21

Have you tried os.rename()?

Just do

os.rename("pdf/pdfFile.pdf", "text/pdfFile.txt")

Upvotes: 2

Related Questions