rename () method syntax is as follows:
os.rename(old,new)
old is a need to modify the directory / file names, new directory is modified / file name, by this method we can easily complete the bulk of the increase in fixed prefix file / directory or batch delete the file / directory fixed prefix.
The following code under Windows and Linux can be used.
Examples are as follows:
Prefixed '[Linuxidc.]':
import os
path='/home/linuxidc/linuxidc.com'
old_dir=os.listdir(path) #获取/home/linuxidc/linuxidc.com目录下的所有文件目录
print("原始目录为 %s"%old_dir)
for i in old_dir:
new_name='[Linuxidc.]'+i
os.rename(i,new_name)
new_dir=os.listdir(path)
print("现在的目录为%s"%new_dir)
After running output:
Delete the prefix '[Linuxidc.]':
import os
path='/home/linuxidc/linuxidc.com'
old_dir=os.listdir(path)
print("原始目录为 %s"%old_dir)
for i in old_dir:
shu=i.rfind(']') #获取到']'的位置
new_name=i[shu+1:]
os.rename(i,new_name)
new_dir=os.listdir(path)
print("现在的目录为%s"%new_dir)
After running output:
In Windows also need to look at the file path should use double slashes //, or an error, this error under Linux generally does not occur.