重命名python中的多个文件,相同的名称但不同的扩展名

时间:2014-08-14 04:11:09

标签: python

我试图更改所有名称相同但扩展名相同的多个文件的名称,我得到的印象是有一个简单的简化方法,但我无法弄清楚如何。

目前我的代码看起来像这样;

import os

def rename_test():
    os.rename ('cheddar.tasty.coor', 'newcheddar.vintage.coor')
    os.rename ('cheddar.tasty.txt', 'newcheddar.vintage.txt')
    os.rename ('cheddar.tasty.csv', 'newcheddar.vintage.csv')

rename_test()

4 个答案:

答案 0 :(得分:1)

import os
def rename(dirpath):
    whitelist = set('txt csv coor'.split())
    for fname in os.listdir(dirpath):
        name, cat, ext = os.path.basename(os.path.join(dirpath, fname)).rsplit(os.path.extsep,2)
        if ext not in whitelist:
            continue
        name = 'new' + name
        cat = 'vintage'
        newname = os.path.extsep.join([name, cat, ext])
        os.rename(os.path.join(dirpath, fname), os.path.join(dirpath, newname))

答案 1 :(得分:0)

您可以使用glob模块。这实际上取决于你想要改进的地方。

for ext in ('*.coor', '*.txt', '*.csv'):
    for filename in glob.glob(ext):
        newname = filename.replace("cheddar.", "newcheddar.").replace(".tasty.", ".vintage.")
        os.rename(filename, newnew)

答案 2 :(得分:0)

def rename_test():
    for ext in "coor txt csv".split():
        os.rename('cheddar.tasty.'+ext, 'newcheddar.vintage.'+ext)

答案 3 :(得分:0)

我会使用listdirreplace - 没有正则表达式,不必解析文件名两次。只需一次替换和相等测试:

import os
for old_filename in os.listdir('.'):
  new_filename = old_filename.replace('cheddar.tasty', 'newcheddar.vintage')
  if new_filename != old_filename:
     os.rename(old_filename, new_filename)
相关问题