# coding=utf-8
import os
from shutil import copyfile
def dealWith():
DST_PREFIX = '改名后'
root = os.getcwd()
dstDir = os.path.sep.join((root, DST_PREFIX))
suffixArray = ['.xlsx', '.csv']
if not os.path.exists(dstDir):
os.makedirs(dstDir)
for parent, ds, fs in os.walk(root):
if not parent == dstDir:
for f in fs:
dirName = os.path.basename(parent)
for suffix in suffixArray:
if f.lower().endswith(suffix):
oldPath = os.path.sep.join((parent, f))
dstPath = os.path.sep.join((dstDir, dirName + "-" + f))
try:
if oldPath.startswith(DST_PREFIX):
print("error {}".format(oldPath))
copyfile(oldPath, dstPath)
except IOError as e:
print("copyoldPath = {}, erro = {}".format(oldPath, e))
finally:
pass
if __name__ == '__main__':
dealWith()
print("main finish.")
文件批量改名
最新推荐文章于 2024-05-29 13:49:18 发布
该代码实现了一个功能,遍历当前工作目录及其子目录,查找特定后缀的文件(如.xlsx和.csv),并将这些文件重命名为包含其原始目录名称的新文件,然后移动到名为'改名后'的新目录下。如果目标文件已存在于新目录中,则会打印错误信息。整个过程在遇到IOError时进行异常处理。
摘要由CSDN通过智能技术生成