这是你想要的吗?
import os, glob
#searches for roots, directory and files
#Path
p=r"C:\\Users\\joao.limberger\\Documents\\Nova Pasta"
# rename arquivo1.txt to arquivo33.txt and arquivo2.txt to arquivo44.txt
renames={"arquivo1.txt":"arquivo33.txt","arquivo2.txt":"arquivo44.txt"}
for root,dirs,files in os.walk(p):
for f in files:
if f in renames.keys():#string you want to rename
try:
os.rename(os.path.join(root , f), os.path.join(root , renames[f]))
print("Renaming ",f,"to",renames[f])
except FileNotFoundError as e:
print(str(e))
看看这是不是你想要的!!!
import os, glob
#searches for roots, directory and files
#Python 2.7
#Path
p=r"C:\\Users\\joao.limberger\\Documents\\Nova Pasta"
# if the substring in the key exists in the filename, replace the substring
# from the value of the key
# if the key is "o1" and the value is "oPrinc1" and the filename is
# arquivo1.txt ... The filename will be renamed to "arquivoPrinc1.txt"
renames={"o1":"oPrinc1","oldSubs":"newSubs"}
for root,dirs,files in os.walk(p):
for f in files:
for r in renames:
if r in f:
newFile = f.replace(r,renames[r],1)
try:
os.rename(os.path.join(root , f), os.path.join(root , newFile))
print "Renaming ",f,"to",newFile
except FileNotFoundError , e:
print str(e)