modify file name util - python

本文介绍了一个在Ubuntu系统中使用Python编写的递归修改文件名的实用工具,能够快速替换文件和目录名称中的子字符串。通过简单的脚本操作,可以实现对指定目录下所有文件和子目录名称的批量修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

modify file name util - python

 

a util script to modify file/folder name recusively, written in python, on ubuntu system,

 

code:

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @author: eric
# @date: 03/04/2012 00:09 am
# @mail: kuchaguangjie@163.com

# this is a python util to modify file names, replace substring in file/folder name with another substring, recursively.
# you should modify variable 'basic_dir' / 'c' / 'c_new', before run this script
# everything, include file/folder recurisively, under the 'basic_dir' will be rename,
# how to run this script, just "./xxx.sh"

# ps: backup before modify is good manners.

import os
import shutil

# basic dir to where files resides
basic_dir = "/tmp/test/"
# substring to replace
c = " "
# new substring
c_new = " "

# function to modify file name recursively
def modify_name(dir,c,c_new):
	# check whether the 2 substring are the same
	if c == c_new:
		print ("2 substring are the same, no need to change")
		return True
	# add '/' to dir end, if necessary,
	if not dir.endswith('/'):
		dir += '/'
	# check dir exists
	if os.path.isdir(dir):  
		print ("dir is: "+dir)
	else:
		print ("dir not exist:" + dir) 
		return False

	# file list
	filelist=[]
	filelist=os.listdir(dir)

	# iterator filelist
	for fname in filelist:
		# change file name if need
		if fname.find(c) >= 0:
			fname_new=fname.replace(c, c_new)   
			print fname_new
			shutil.move(dir+fname,dir+fname_new)
			fname = fname_new

		# call the function recurisively on the sub dir
		if os.path.isdir(dir+fname):
			modify_name(dir+fname,c,c_new)

# the entry, call the function, with the basic dir
modify_name(basic_dir,c,c_new);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值