python用os修改文件名_Python中的os模块与自动修改文件名

一、os模块中的常用命令

python中的os模块用来进行一些文件操作,对于常用命令整理为如下导图:

c53a72f00df3

os模块中的常用命令

二、自动修改文件名

该函数可实现的功能:

批量给文件夹下的文件名添加前缀或者后缀

批量修改文件名中的某个字符串为新字符串

修改文件名时可指定文件类型,并过滤掉文件夹

# 自动修改文件名,给文件名统一添加某个后缀

import os

def filename_modify(dir,addstr='',position="end",oldstr='',newstr='',filetype=None):

# 判断文件夹是否存在

if os.path.exists(dir)==False:

raise Exception("dir is not exist")

# 获得文件列表

for file in os.listdir(dir):

# 分割文件名和扩展名

file_name = os.path.splitext(file)[0]

file_expand = os.path.splitext(file)[1]

print(file_name,file_expand)

# 如果是文件夹,不修改文件名

if os.path.isdir(os.path.join(dir,file)):

continue

# 过滤文件类型

if filetype!=None and filetype not in file_expand:

continue

if position=="end":

# 修改文件名

newname = file_name+addstr+file_expand

elif position=="head":

newname = addstr + file_name +file_expand

elif position=="replace":

newname = file_name.replace(oldstr,newstr)+file_expand

oldpath = os.path.join(dir,file)

newpath = os.path.join(dir,newname)

os.rename(oldpath,newpath)

filename_modify("./test",

addstr="简书-",

position="head",

oldstr="",

newstr="",

filetype=".xlsx")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值