简体   繁体   English

python3 os.rename()不会重命名名称中带有“Copy”字样的文件

[英]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!! 我正在尝试使用python 3.7.3重命名我的一个文件夹中的一堆文件,并且它不会重命名那些在其中包含“复制”一词的文件。它还会打印旧的文件名。重命名后重命名!!

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' '7527复制'

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: 由于此检查,它不会在名称中使用Copy重命名文件:

if not "py" in i:   #so it won't rename this file

If Copy is in the name, then py is in the name. 如果Copy在名称中,则py在名称中。

Maybe you should have 也许你应该有

if not i.endswith('.py'):

instead. 代替。

If you want an updated directory listing, you have to call listdir again. 如果需要更新的目录列表,则必须再次调用listdir

directory = os.listdir(os.getcwd()) # get updated contents

for i in directory:
    print(i)  

You're only assigning directory once. 你只需要分配一次directory You need to update it by calling listdir again. 您需要再次调用listdir来更新它。

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]))

updated_directory = os.listdir(os.getcwd()) # NEW

for i in updated_directory:
    print(i)  #why does this print the old names instead of the new ones?!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM