【问题标题】:Python - Rename files except specific extensionsPython - 重命名文件(特定扩展名除外)
【发布时间】:2020-11-20 17:30:44
【问题描述】:

我想重命名当前目录中的一些文件

所以当我尝试下面的代码时,它也会更改我的 Script.py 文件扩展名

现在我想将 .py 扩展名排除在重命名之外

或者是否可以在不影响文件扩展名的情况下重命名文件?

我尝试的代码是:

import os 

def rename(path, new_name, numbering, extension):
    list = os.listdir(path)
    os.chdir(path)
    count = numbering
    for i in list:
    os.rename(i, new_name + str(count).zfill(2) + '.' + extension)
    count += 1

path = os.path.abspath('./')

rename(path, 'New', 1, 'txt')

【问题讨论】:

  • 欢迎来到 Stack Overflow。如果它回答了您的问题,请不要忘记接受答案(勾选答案旁边的复选标记)。这样,您的问题就不再显示为未回答。还投票赞成好的答案。 – 从这里开始,请使用tour,阅读what's on-topic,并查看How to Ask a Good Question

标签: python file rename


【解决方案1】:
import os 

def rename(path, new_name, numbering, extension):
    list = os.listdir(path)
    os.chdir(path)
    count = numbering
    for i in list:
       if not i.endswith(".py"):
          os.rename(i, new_name + str(count).zfill(2) + '.' + extension)
          count += 1

path = os.path.abspath('./')

rename(path, 'New', 1, 'txt')

【讨论】:

  • 我想这很有帮助
猜你喜欢
  • 2014-03-16
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多