【问题标题】:python3 os.rename() won't rename files with the word 'Copy' in namepython3 os.rename() 不会重命名名称中带有“复制”一词的文件
【发布时间】:2019-05-23 06:16:54
【问题描述】:

我正在尝试使用 python 3.7.3 重命名我的一个文件夹中的一堆文件,它不会重命名其中包含“复制”一词的文件。它还会打印旧文件名重命名后确实重命名的那些!!

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

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

但它不会重命名:

'7527 复制'

这是我开始使用的文件名之一,它不会重命名(只是为了更加清楚):

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

编辑:这是我在这里的第一个问题,我不知道我在做什么,所以请耐心等待

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    由于此检查,它不会重命名名称中带有 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)  
    

    【讨论】:

      【解决方案2】:

      您只分配了一次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?!!
      

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 2021-11-02
        • 2012-09-26
        • 2018-01-13
        • 1970-01-01
        • 2016-04-26
        • 2014-01-29
        • 1970-01-01
        • 2020-01-12
        相关资源
        最近更新 更多