Python Forum

Full Version: Edit Filename
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am new to python and would like to know how to quickly change the end of my link to multiple files according to the following criteria: I only want to change the last letter (range A to F) and the last number (range 0.1 at 0.6).

See the code:

import os

os.rename (r'C: \ Users \ Name \ Downloads \ foo14A.png ', r'C: \ Users \ Name \ Downloads \ foo149.1.png')

print ('ok')
Your_new_file = "foo14{}.png".format(A)

Read up on placeholders aka "{}"
Can you tell why or the code doesn't work?

import os

for i in range(ord('a'),ord('f')+1):
for j in range(1,6):
os.rename(r'C:\Users\Name\Downloads\ppl15{i}.png',r'C:\Users\Name\Downloads\ppl139.{j}.png')

print('ok')
Well, it probably has to do with it not looking one single bit like my example.

Learn the .format() function. And ord() returns an integer, not a letter.
Use code tag @arthur_cti.
This example should help.
import os

path = 'C:/Users/Name/Downloads/'
#os.chdir(path) # make sure that in right path or need to use os.path.join()
for i in range(ord('a'), ord('f')+1):
    print(f'{path}ppl15{chr(i)}.png', f'{path}ppl139.{i-96}.png')

print('ok')
Output:
C:/Users/Name/Downloads/ppl15a.png C:/Users/Name/Downloads/ppl139.1.png C:/Users/Name/Downloads/ppl15b.png C:/Users/Name/Downloads/ppl139.2.png C:/Users/Name/Downloads/ppl15c.png C:/Users/Name/Downloads/ppl139.3.png C:/Users/Name/Downloads/ppl15d.png C:/Users/Name/Downloads/ppl139.4.png C:/Users/Name/Downloads/ppl15e.png C:/Users/Name/Downloads/ppl139.5.png C:/Users/Name/Downloads/ppl15f.png C:/Users/Name/Downloads/ppl139.6.png ok
My apologies.
@snippsat and @michael1789

This os.rename does not seem to work, would you know a solution to these problems?

import os
 
path = 'C:/Users/Name/Downloads/Test'

for i in range(ord('a'), ord('f')+1):
    os.rename(r'{path}ppl15{chr(i)}.png', r'{path}ppl139.{i}.png')
 
print('Finish')

I got a solution. I'll post, if anyone can improve, post here too. Thank you! My first contact with the community was very productive. Python is the future.

import os

for i in range(ord('a'), ord('f')+1):
    os.rename(r'C:/Users/Name/Downloads/Teste/'+'ppl15'+ chr(i)+'.'+'png', 'C:/Users/Name/Downloads/Teste/'+'ppl139'+'.'+str(i-96)+'.'+'png')

print('Finish')
It's not r but f i use string formatting f-string.
Test working.
import os

path = 'C:/Users/Name/Downloads/'
os.chdir(path)
for i in range(ord('a'), ord('c')+1):
    os.rename(f'{path}ppl15{chr(i)}.png', f'{path}ppl139.{i}.png')
print('Finish')
These filename most exists in path Download.
ppl15a.png
ppl15b.png
ppl15c.png
My output:
Output:
ppl139.97.png ppl139.98.png ppl139.99.png