I'm trying to rename a bunch of files in one of my folders using python 3.7.3 and it won't rename the ones that have the word "Copy" in them.. it also prints the old file names for the ones it does rename after renaming them!!
I thought it was because they had white spaces or hyphens or letters in them so I added some to other files' names but it did rename them.. for example: it would rename:
'10 60'
'54 - 05'
'9200 d'
but it won't rename:
'7527 Copy'
this is one of the file names I started with that it won't rename (just to be extra clear):
'6576348885058201279439757037938886093203209992672224485458953892 - Copy'
Here's my code:
import os
from random import randint
def how_many_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
directory = os.listdir(os.getcwd())
for i in directory:
if not "py" in i: #so it won't rename this file
os.rename(i, str(how_many_digits(4)) + str(os.path.splitext(i)[1]))
for i in directory:
print(i) #why does this print the old names instead of the new ones?!!
EDIT: this is my first question ever on here and I have no idea what I'm doing so bear with me
It won't rename files with Copy
in the name because of this check:
if not "py" in i: #so it won't rename this file
If Copy
is in the name, then py
is in the name.
Maybe you should have
if not i.endswith('.py'):
instead.
If you want an updated directory listing, you have to call listdir
again.
directory = os.listdir(os.getcwd()) # get updated contents
for i in directory:
print(i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With