答案 0 :(得分:13)
试试这个:
import os
pathiter = (os.path.join(root, filename)
for root, _, filenames in os.walk(folder)
for filename in filenames
)
for path in pathiter:
newname = path.replace('ES.txt', '_ES_manual.txt')
if newname != path:
os.rename(path,newname)
答案 1 :(得分:5)
对hughdbrown的答案有更广泛的看法。此代码可用于删除任何特定字符或字符集。
import os
paths = (os.path.join(root, filename)
for root, _, filenames in os.walk('C:\FolderName')
for filename in filenames)
for path in paths:
# the '#' in the example below will be replaced by the '-' in the filenames in the directory
newname = path.replace('#', '-')
if newname != path:
os.rename(path, newname)
答案 2 :(得分:3)
for root, dirs, filenames in os.walk(folder):
to_write = ['root == %s\n' % root]
for filename in filenames:
filename_zero, fileext = os.path.splitext(filename)
newname = "%s_%s_manual%s" % (filename_zero[:-2],filename_zero[-2:],fileext)
tu = (os.path.join(root, filename), os.path.join(root, newname))
to_write.append('%s --> %s\n' % tu)
os.rename(*tu)
print '\n'.join(to_write)
答案 3 :(得分:2)
答案 4 :(得分:0)
这是另一种不使用 os.path.join
或 os.walk
的替代方法:
import os
fileLocation = "C:\\Documents and Settings\\DuffA\\Bureaublad\\test\\"
fileList = os.listdir(fileLocation)
for ii in fileList:
newName = ii.replace('ES','_ES_Manual')
if newName != ii:
os.rename(fileLocation+ii,fileLocation+newName)