Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 os.rename() won't rename files with the word 'Copy' in name

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

like image 955
xSabotagex Avatar asked May 22 '19 21:05

xSabotagex


1 Answers

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)  
like image 186
khelwood Avatar answered Nov 15 '22 07:11

khelwood