对Python 检查文件名是否规范的实例详解


Posted in Python onJune 10, 2019

如下所示:

# coding=utf-8
import os
import os.path
import re
import array
import cmd
import pdb
import pickle
import tempfile
import subprocess
 
 
# rootPath = os.getcwd()
# print rootPath
rootPath = raw_input('The Check Path:')
nonCheckDir = raw_input('The Non Check DirName(DirName1;DirName2):')
nonCheckDirList = []
if nonCheckDir:
  nonCheckDirList = nonCheckDir.split(';')
# 路径字典
pathDic = {}
 
# 新建文件夹 os.path.isdir(rootdir+'/logout') 判断指定目录下该文件夹是否存在
if not os.path.isdir(rootPath+'/logout'):
  os.makedirs(rootPath + '/logout')
logPath=os.path.join(rootPath,'logout')
 
nonstandard_filename_path = open(logPath+'/nonstandard_filename_path.txt','w')
 
# 标准的符号库
num = "0123456789"
word = "abcdefghijklmnopqrstuvwxyz"
sym = "_."
# 符号库
symBank = []
for key in word:
  symBank.append(key)
for key in num:
  symBank.append(key)
for key in sym:
  symBank.append(key)
 
def GetAllDir(getPath):
  # print (getPath)
  paths = os.listdir(getPath)
  for dirName in paths:
    dirPath = os.path.join(getPath,dirName)
    if os.path.isdir(dirPath) and dirName != '.svn':
      # print dirPath
      relPath = dirPath[len(rootPath)+1:len(dirPath)]
      # print relPath
      if not nonCheckDirList.__contains__(relPath):
        pathDic[relPath] = dirPath
        GetAllDir(dirPath)
 
def GetAllFile(getPath):
  files = os.listdir(getPath)
  for fileName in files:
    filePath = os.path.join(getPath,fileName)
    if fileName.endswith('.png') or fileName.endswith('.PNG'):
      fileName = fileName[0:fileName.index('.')]
      if not set(fileName).issubset(symBank):
        # print fileName
        # print filePath
        nonstandard_filename_path.write(filePath + '\n')
      else:
        # (r'_[\d]*[x|X][\d]*\d') 正则表达式 (_100x100)
        sign = re.search(r'_[\d]*[x|X][\d]*\d',fileName,re.M|re.I)
        if sign:
          nonstandard_filename_path.write(filePath + '\n')
 
if __name__ == '__main__':
  print ('main')
  pathDic['curPath'] = rootPath
  GetAllDir(rootPath)
  for key in pathDic:
    # print key
    GetAllFile(pathDic[key])
 
  # line = "image_500100000"
  # obj = re.search(r'_[\d]*[x|X][\d]*\d',line,re.M|re.I)
  # line = line.replace(obj.group(),'=')
  # if obj:
  #   print obj.group()
  # else:
  #   print ("==-")
  # line1 = "image_500x100"
  # obj1 = re.search(r'[a-z0-9_]*',line1,re.M)
  # print obj1.group()

新建bat后缀文件

find_nonstandard_name.exe -c
@pause

修改后脚本

# coding=utf-8
import os
import os.path
import re
import array
import cmd
import pdb
import pickle
import tempfile
import subprocess
import sys
import getopt
 
rootPath = ""
nonCheckDirList = sys.argv[1:]
opts, args = getopt.getopt(sys.argv[1:],"cs:",["cPath="])
for opt,arg in opts:
  if opt == '-c':
    rootPath = os.getcwd()
  elif opt in ("-s","--cPath"):
    rootPath = arg
# 路径字典
pathDic = {}
 
# 新建文件夹 os.path.isdir(rootdir+'/logout') 判断指定目录下该文件夹是否存在
if not os.path.isdir(rootPath+'/logout'):
  os.makedirs(rootPath + '/logout')
logPath=os.path.join(rootPath,'logout')
 
nonstandard_filename_path = open(logPath+'/nonstandard_filename_path.txt','w')
 
def GetAllDir(getPath):
  # print (getPath)
  paths = os.listdir(getPath)
  for dirName in paths:
    dirPath = os.path.join(getPath,dirName)
    if os.path.isdir(dirPath) and dirName != '.svn':
      # print dirPath
      relPath = dirPath[len(rootPath)+1:len(dirPath)]
      # print relPath
      if not nonCheckDirList.__contains__(relPath):
        pathDic[relPath] = dirPath
        GetAllDir(dirPath)
 
def GetAllFile(getPath):
  files = os.listdir(getPath)
  for fileName in files:
    filePath = os.path.join(getPath,fileName)
    if fileName.endswith('.png') or fileName.endswith('.PNG'):
      fileName = fileName[0:fileName.index('.')]
      firstSign = re.search(r'^[a-z0-9_]*$',line1,re.M)
      if firstSign:
        # print filePath
        # (r'_[\d]*[x|X][\d]*\d') 正则表达式 (_100x100)
        sign = re.search(r'_[\d]*[x|X][\d]*\d', fileName, re.M | re.I)
        if sign:
          print fileName
          nonstandard_filename_path.write(filePath + '\n')
      else:
        print fileName
        nonstandard_filename_path.write(filePath + '\n')
 
if __name__ == '__main__':
  print ('main')
  pathDic['curPath'] = rootPath
  GetAllDir(rootPath)
  for key in pathDic:
    # print key
    GetAllFile(pathDic[key])

添加检查文件重名功能

# coding=utf-8
import os
import os.path
import re
import array
import cmd
import pdb
import pickle
import tempfile
import subprocess
import sys
import getopt
 
nonCheckDirList = sys.argv[1:]
rootPath = os.getcwd()
checkRepetPathList = []
if nonCheckDirList:
  rootPath = os.path.realpath(os.path.join(os.getcwd(),nonCheckDirList[0]))
  if nonCheckDirList[0] == "./":
    rootPath = os.getcwd()
  for _path in nonCheckDirList:
    # -- 检查重命名路径
    _cmdRepet = _path[0:2]
    if _cmdRepet == "/r":
      repetPath = _path[len(_cmdRepet):len(_path)]
      print repetPath
      checkRepetPathList.append(repetPath)
print rootPath + '\n'
# 路径字典
pathDic = {}
# 重名路径字典
repetDic = {}
# 新建文件夹 os.path.isdir(rootdir+'/logout') 判断指定目录下该文件夹是否存在
 
# if not os.path.isdir(rootPath+'/logout'):
#   os.makedirs(rootPath + '/logout')
# logPath=os.path.join(rootPath,'logout')
logPath = os.getcwd()
nonstandard_filename_path = open(logPath+"\\"+u"不规范命名文件".encode("GBK") + ".txt",'w')
 
def GetAllDir(getPath):
  # print (getPath)
  paths = os.listdir(getPath)
  for dirName in paths:
    dirPath = os.path.join(getPath,dirName)
    if os.path.isdir(dirPath) and dirName != '.svn':
      # print dirPath
      relPath = dirPath[len(rootPath)+1:len(dirPath)]
      # print relPath
      if not nonCheckDirList.__contains__(relPath):
        pathDic[relPath] = dirPath
        GetAllDir(dirPath)
 
def GetAllFile(getPath):
  files = os.listdir(getPath)
  for fileName in files:
    filePath = os.path.join(getPath,fileName)
    if fileName.endswith('.png') or fileName.endswith('.PNG'):
      fileName = fileName[0:fileName.index('.')]
      firstSign = re.search(r'^[a-z0-9_]*$',fileName,re.M)
      if firstSign:
        # print filePath
        # (r'_[\d]*[x|X][\d]*\d') 正则表达式 (_100x100)
        sign = re.search(r'_[\d]*[x|X][\d]*\d', fileName, re.M | re.I)
        if sign:
          print fileName
          nonstandard_filename_path.write(filePath + '\n')
      else:
        print fileName
        nonstandard_filename_path.write(filePath + '\n')
 
def CheckRepetFile(getPath):
  if checkRepetPathList:
    paths = os.listdir(getPath)
    for dirName in paths:
      dirPath = os.path.join(getPath, dirName)
      if os.path.isdir(dirPath) and dirName != '.svn':
        # print dirPath
        relPath = dirPath[len(rootPath) + 1:len(dirPath)]
        # print relPath
        repetDic[relPath] = dirPath
        CheckRepetFile(dirPath)
 
 
imageList = []
repetImagePath = []
def GetCheckRepetFile(getPath):
  files = os.listdir(getPath)
  for fileName in files:
    filePath = os.path.join(getPath, fileName)
    if fileName.endswith('.png') or fileName.endswith('.PNG'):
      # print filePath
      imageList.append(fileName)
      repetImagePath.append(filePath)
 
repet_filename_path = open(logPath+"\\"+u"重复命名文件".encode("GBK") + ".txt",'w')
 
if __name__ == '__main__':
  # print ('main')
  pathDic['curPath'] = rootPath
  GetAllDir(rootPath)
  for key in pathDic:
    # print key
    GetAllFile(pathDic[key])
  print '\n' + "The Logout Path:" + logPath+"\\"+u"不规范命名文件".encode("GBK") + ".txt"
 
 
  repetDic['curPath'] = rootPath
  # 检查重复文件路径列表
  for __path in checkRepetPathList:
    _repetPath = os.path.join(rootPath, __path)
    CheckRepetFile(_repetPath)
  # 遍历路径获得所有图片
  for key in repetDic:
    GetCheckRepetFile(repetDic[key])
  _newImageList = []
  for image in imageList:
    repetCount = imageList.count(image)
    if repetCount > 1 :
      if not image in _newImageList:
        _newImageList.append(image)
  for repetImage in _newImageList:
    print repetImage
    repet_filename_path.write(repetImage + '\n')
    for repetPathPath in repetImagePath:
      fileNameName = os.path.basename(repetPathPath)
      if repetImage == fileNameName:
        repet_filename_path.write(repetPathPath + '\n')
        # print repetPathPath
  print '\n' + "The Logout Path:" + logPath+"\\"+u"重复命名文件".encode("GBK") + ".txt"

以上这篇对Python 检查文件名是否规范的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
pycharm 使用心得(九)解决No Python interpreter selected的问题
Jun 06 Python
Python中字典的基本知识初步介绍
May 21 Python
详解详解Python中writelines()方法的使用
May 25 Python
python实现线程池的方法
Jun 30 Python
python创建临时文件夹的方法
Jul 06 Python
利用django如何解析用户上传的excel文件
Jul 24 Python
浅谈Python中的zip()与*zip()函数详解
Feb 24 Python
Python用61行代码实现图片像素化的示例代码
Dec 10 Python
深入浅析python的第三方库pandas
Feb 13 Python
python3+opencv 使用灰度直方图来判断图片的亮暗操作
Jun 02 Python
浅谈keras使用预训练模型vgg16分类,损失和准确度不变
Jul 02 Python
浅谈Python 中的复数问题
May 19 Python
java判断三位数的实例讲解
Jun 10 #Python
Python字符串的一些操作方法总结
Jun 10 #Python
利用selenium爬虫抓取数据的基础教程
Jun 10 #Python
Python 监测文件是否更新的方法
Jun 10 #Python
python实现随机漫步方法和原理
Jun 10 #Python
使用python判断jpeg图片的完整性实例
Jun 10 #Python
关于Python作用域自学总结
Jun 10 #Python
You might like
ThinkPHP3.1.x修改成功与失败跳转页面的方法
2017/09/29 PHP
php利用ob_start()清除输出和选择性输出的方法
2018/01/18 PHP
Laravel框架控制器的middleware中间件用法分析
2019/09/30 PHP
JS 事件绑定函数代码
2010/04/28 Javascript
jquery cookie实现的简单换肤功能适合小网站
2013/08/25 Javascript
javascript的switch用法注意事项分析
2015/02/02 Javascript
浅谈JavaScript的事件
2015/02/27 Javascript
jQuery处理json数据返回数组和输出的方法
2015/03/11 Javascript
使用JS实现图片展示瀑布流效果(简单实例)
2016/09/06 Javascript
jstree创建无限分级树的方法【基于ajax动态创建子节点】
2016/10/25 Javascript
微信小程序开发之选项卡(窗口底部TabBar)页面切换
2017/04/12 Javascript
微信小程序删除处理详解
2017/08/16 Javascript
JQuery 又谈ajax局部刷新
2017/11/27 jQuery
关于vue v-for循环解决img标签的src动态绑定问题
2018/09/18 Javascript
JavaScript"模拟事件"的注意要点详解
2019/02/13 Javascript
解决vue的router组件component在import时不能使用变量问题
2020/07/26 Javascript
vue axios请求成功却进入catch的原因分析
2020/09/08 Javascript
Javascript实现单选框效果
2020/12/09 Javascript
rhythmbox中文名乱码问题解决方法
2008/09/06 Python
python实现的生成随机迷宫算法核心代码分享(含游戏完整代码)
2014/07/11 Python
django使用xlwt导出excel文件实例代码
2018/02/06 Python
深入理解Python 关于supper 的 用法和原理
2018/02/28 Python
在Django中输出matplotlib生成的图片方法
2018/05/24 Python
Python用Try语句捕获异常的实例方法
2019/06/26 Python
Python面向对象程序设计之继承、多态原理与用法详解
2020/03/23 Python
Keras自定义IOU方式
2020/06/10 Python
tensorflow使用CNN分析mnist手写体数字数据集
2020/06/17 Python
Python常用GUI框架原理解析汇总
2020/12/07 Python
经典c++面试题二
2015/08/14 面试题
个人自我鉴定
2013/11/07 职场文书
高中教师评语大全
2014/04/25 职场文书
2015年实习生工作总结报告
2015/04/28 职场文书
创业计划书之小型广告公司
2019/10/22 职场文书
css3新特性的应用示例分析
2022/03/16 HTML / CSS
剧场版《转生恶役只好拔除破灭旗标》公开最新视觉图 2023年上映
2022/04/02 日漫
Vue OpenLayer测距功能的实现
2022/04/20 Vue.js