def listFiles(dir):
rootdir = dir
for root, subFolders, files in os.walk(rootdir):
for file in files:
yield os.path.join(root,file)
return
for f in listFiles(target):
if pattern in f:
os.rename(f,f.replace(pattern,'REPLACED'))
我有一个文件,例如:
"C:\Dir3.30\file_3.30.xml"
如果我这样做
os.rename(f,f.replace(pattern,'REPLACED'))
这两种情况都会被取代。 如何确保仅替换文件名
我想:
"C:\Dir3.30\file_REPLACED.xml"
答案 0 :(得分:1)
使用os.path.split()
拆分文件名,仅在名称上调用str.replace()
,然后重新加入:
path, name = os.path.split(f)
os.rename(f, os.path.join(path, name.replace(pattern, 'REPLACED')))