python - os module example

  1. In the current directory new directory img, which contains multiple files, each file name is not the same (X4G5.png)
  2. The current list of all img suffix name changed to the end of .jpg .png
import random
import string
import os

def gen_code(len=4):
    # 随机生成四位随机数
    li = random.sample(string.ascii_letters+string.digits,len)
    # print(li)
    return  ''.join(li)

def creat_file():
    # 随机生成多个文件名
    li = {gen_code() for i in range(100)}
    os.mkdir('img')
    for name in li:
        os.mknod('img/' + name + '.png')
# creat_file()

def modify_suffix(dirname,old_suffix,new_suffix):
    """
    :param dirname: 要操作的目录
    :param old_suffix: 只前的后缀名
    :param new_suffix: 新的后缀名
    :return:
    """
    # 1.要判断查找的目录是否存在 如果不存在 报错
    if os.path.exists(dirname):
        # 2.找出所有以old_suffix(.png)结尾的文件
        pngfile = [filename for filename in os.listdir(dirname)
                   if filename.endswith(old_suffix)]
        # 3.将后缀名和文件名分离 留下文件名
        basefile = [os.path.splitext(filename)[0]
                    for filename in pngfile]
        # 4.重新命名文件
        for filename in basefile:
            oldname = os.path.join(dirname,filename+old_suffix)
            newname = os.path.join(dirname,filename+new_suffix)
            os.rename(oldname,newname)
            print('%s命名为%s成功' %(oldname,newname))
    else:
        print('%s 不存在,不能操作' %(dirname))

modify_suffix('img','.html','.php')
Published 68 original articles · won praise 0 · Views 527

Guess you like

Origin blog.csdn.net/qq_42024433/article/details/103940212