python批量修改文件夹
1、批量修改文件夹名称
2、renames()方法语法格式如下:
》import os 》os.renames(old, new)
old -- 要重命名的目录
new --文件或目录的新名字。甚至可以是包含在目录中的文件,或者完整的目录树。
且old, new必须是str类型,才能更新。
#--报错实例代码
import os os.renames("111111", 555555) Traceback (most recent call last): File "D:\yuexiang_sc\imeiss\dome_44.py", line 17, in <module> os.renames("111111", 555555) File "D:\python3.9\lib\os.py", line 269, in renames head, tail = path.split(new) File "D:\python3.9\lib\ntpath.py", line 185, in split p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not int Process finished with exit code 1
2、小伙伴们可以参考如下代码,需要用到可以进行优化~
1 import os 2 3 4 def ceshi(text, num): 5 temp = int(text.split('P')[1]) # 修改方法中2处“P” 即可 6 for _ in range(num): 7 temp += 1 8 res = "P" + str(temp).zfill(5) 9 return res 10 11 12 def get_all(cwd,shuzi): 13 result = [] 14 get_dir = os.listdir(cwd) # 遍历当前目录,获取文件列表 15 for i in get_dir: 16 sub_dir = os.path.join(cwd, i) 17 if os.path.isdir(sub_dir) == True: # 如果当前仍然是文件夹。将文件夹放到列表中 18 ax = os.path.basename(sub_dir) 19 result.append(ax) 20 21 try: 22 float(result[0]) # float(值)判断值是否能转换成浮点数,否走except 23 print("1") 24 result = list(map(int, result)) 25 result.sort(reverse=False) # reverse = False 升序(默认) 26 result = list(map(str, result)) 27 for j in range(len(result)): 28 old = cwd + '\\' + result[j] 29 new = cwd + '\\' + ceshi(shuzi, j) 30 print("原来数据:%s====%s" % (old, new)) 31 os.renames(old, new) # os.renames(路径+修改前文件名称,路径+修改后文件名称 ) 32 except(ValueError): 33 print("2") 34 result.sort() 35 for j in range(len(result)): 36 old = cwd + '\\' + result[j] 37 new = cwd + '\\' + ceshi(shuzi, j) 38 print("原来数据:%s====%s" % (old, new)) 39 os.renames(old, new) # os.renames(路径+修改前文件名称,路径+修改后文件名称 ) 40 41 42 if __name__ == "__main__": 43 cur_path = "C:\\Users\ysxh\Desktop\img\img" # 修改此处路径即可 44 shuzi = "P00000" #从几开始,就写几 45 print(cur_path) 46 get_all(cur_path,shuzi)
执行结果如下: