我有一个文件夹,里面有很多这样的文件:
2012-05-09.txt
2012-05-10.txt
2012-05-11.txt
etc.
现在我想删除连字符并添加“_PHOTOS_LOG”,它最终看起来像这样:
20120509_PHOTOS_LOG.txt
20120510_PHOTOS_LOG.txt
20120511_PHOTOS_LOG.txt
etc.
怎么做 ?
这就是现在的代码:
//updated the code, now its working
import os
import glob
import os.path
import sys
src = 'D:\\testing/hyphen1'
src = r'D:\testing\test'
for fn in os.listdir(src):
new_filename = fn.replace('-','').replace('.txt', '_PHOTOS_LOG.txt')
fn = os.path.join(src, fn)
new_filename = os.path.join(src, new_filename)
try:
os.rename(fn, new_filename)
except (WindowsError, OSError):
print 'Error renaming "%s" to "%s"' % (fn, new_filename)
print sys.exc_info()[1]