zoukankan      html  css  js  c++  java
  • Python批量重命名

    某无聊的下午的一个小需求

    1 import os
    2 dirPath = r''    #路径
    3 format = r''    #后缀
    4 name = 0
    5 for file in os.listdir(dirPath):
    6     oldPath = '%s\%s'%(dirPath, file)
    7     newPath = '%s\%s.%s'%(dirPath, name, format)
    8     name += 1
    9     os.rename(oldPath, newPath)
    ......

    然后今晚(20160729)想要根据文件内容重命名来着.....

    结果智障了半个小时,没关闭文件就想rename...........

     1 import os
     2 import re
     3 
     4 rootpath = r'' #路径
     5 
     6 paten = r'(?<=Title:
    ).*' #按照需求写正则
     7 os.chdir(rootpath) #脚本和文件们不在同一个文件夹是需将当前路径改一下
     8 
     9 for i in os.listdir(rootpath):
    10     oldname = os.path.normpath(os.path.join(rootpath, i))
    11     file = open(i, 'r')
    12     try:
    13         newname = re.findall(paten, file.read())[0] + '.txt'
    14         newname = os.path.normpath(os.path.join(rootpath, newname))
    15         file.close() #先关闭再rename
    16         os.rename(oldname, newname)
    17     except IndexError as e: #有一个文件是跟其他不同的....在try的下一行产生IndexError
    18         file.close() #记得关闭文件......
    19         print(i)
    View Code
  • 相关阅读:
    C#第八节课
    C#第七节课
    C#第六节课
    supervisor进程管理的使用
    oracle分区表
    Zabbix配置邮件监控
    python连接oracle数据库
    json内存级非关系数据库
    Oracle 12c CDB PDB 安装/配置/管理
    Let's Encrypt免费泛域名证书申请
  • 原文地址:https://www.cnblogs.com/book-book/p/5650402.html
Copyright © 2011-2022 走看看