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.30file_3.30.xml"
如果我这样做
os.rename(f,f.replace(pattern,'REPLACED'))
两个出现将被替换。如何确保只替换文件名
我想:
"C:Dir3.30file_REPLACED.xml"
将文件名与os.path.split()
分开,仅在名称上调用str.replace()
,然后重新连接:
path, name = os.path.split(f)
os.rename(f, os.path.join(path, name.replace(pattern, 'REPLACED')))