Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Edit Filename
#1
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')
Reply
#2
Your_new_file = "foo14{}.png".format(A)

Read up on placeholders aka "{}"
Reply
#3
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')
Reply
#4
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.
Reply
#5
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
Reply
#6
My apologies.
Reply
#7
@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')
Reply
#8
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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020