os.renames(old, new)
官方的解释:
Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned until either the whole path is consumed or a nonempty directory is found.
Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file.
google翻译为:
超级重命名; 根据需要创建目录并删除任何留空的目录。 像重命名一样工作,除了首先尝试创建使新路径名良好所需的任何中间目录。 重命名后,与旧名称最右侧路径段对应的目录将被修剪,直到整个路径被消耗或找到非空目录。
注意:如果您缺乏取消链接叶目录或文件所需的权限,此功能可能会因新目录结构而失败。
源代码部分:
#传入两个地址,为绝对路径
def renames(old, new):
#将新的路径按照最后一个'\'分割成两部分,即头和尾,即根目录和子文件名,例如’C:\\' 和 '1.jpg'
head, tail = path.split(new)
#判断头、尾是否存在,根目录不存在,则创建目录
if head and tail and not path.exists(head):
makedirs(head)
#开始改名
rename(old, new)
#同样分割处理
head, tail = path.split(old)
#使用os.rename()不能对根目录进行改变
if head and tail:
try:
removedirs(head)
except OSError:
pass
小结:os.rename()是一个更改文件名的基本命令,只能对根目录下的文件名进行更改,而os.renames()可以对根目录进行更改,在os.renames()内部嵌套os.name()。
这里也提供一个网站,可以查询python的一些内置方法的源代码和使用说明。
另外,也可以查询一些其他语言的源码。有些方法如果不是很清楚,可以直接查看源码。
栗子
将文件夹中的图片名称批量更改,保存在原目录下。
import os
def change_name(path):
file_list = os.listdir(path)
for i,each_file in enumerate(file_list):
old_name = each_file
#按照序号排列命名,只需要改这里和路径即可
new_name = 'cat_' + str(i) + '_1.jpg'
#这种情况下,两种方法没有区别,都能执行
# os.rename(os.path.join(path,old_name),os.path.join(path,new_name))
os.renames(os.path.join(path, old_name), os.path.join(path, new_name))
print('成功将 {} 重命名为:{}'.format(old_name,new_name))
if __name__ == '__main__':
change_name(path=r'F:/pycharm文件/hello pytorch/DATAS/orginal_image/training/')
效果如下: