Python3的os.rename()函数无法重命名包含“Copy”单词的文件名。

7

我正在使用Python 3.7.3尝试重命名一个文件夹中的一堆文件,但它不会重命名其中带有单词"Copy"的文件..在重命名后,它还会打印已重命名文件的旧文件名!!

我认为这是因为它们有空格、连字符或字母,所以我将它们添加到其他文件的名称中,但它没有重命名它们。例如:它会重命名:

'10 60'
'54 - 05'
'9200 d' 

但它无法重命名:
'7527 Copy'
这是我开始使用的其中一个文件名,它无法重命名(只是为了更加清楚明了)。
'6576348885058201279439757037938886093203209992672224485458953892 - Copy'

以下是我的代码:

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?!!

编辑:这是我在这里的第一个问题,我不知道我在做什么,所以请谅解。

这个问题与IT技术无关。
2个回答

12

由于以下检查,它不会重命名文件名中带有Copy的文件:

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

如果名称中含有“Copy”,那么名称中也会含有“py”。 也许你应该有...
if not i.endswith('.py'):

相反,如果你想要更新的目录列表,你需要再次调用listdir

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

for i in directory:
    print(i)  

3

您只对directory进行了一次赋值。您需要通过再次调用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?!!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接