对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 相关文章推荐
深入源码解析Python中的对象与类型
Dec 11 Python
Python自定义主从分布式架构实例分析
Sep 19 Python
python列表的增删改查实例代码
Jan 30 Python
Python计算一个给定时间点前一个月和后一个月第一天的方法
May 29 Python
python如何爬取个性签名
Jun 19 Python
python 批量修改/替换数据的实例
Jul 25 Python
基于python 等频分箱qcut问题的解决
Mar 03 Python
Python+Django+MySQL实现基于Web版的增删改查的示例代码
May 13 Python
Python 程序报错崩溃后如何倒回到崩溃的位置(推荐)
Jun 23 Python
Windows环境下Python3.6.8 importError: DLLload failed:找不到指定的模块
Nov 01 Python
Python 排序最长英文单词链(列表中前一个单词末字母是下一个单词的首字母)
Dec 14 Python
matplotlib阶梯图的实现(step())
Mar 02 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
精致的人儿就要挑杯子喝咖啡
2021/03/03 冲泡冲煮
Linux下CoreSeek及PHP扩展模块的安装
2012/09/23 PHP
php获取qq用户昵称和在线状态(实例分析)
2013/10/27 PHP
PHP CURL获取cookies模拟登录的方法
2013/11/04 PHP
PHP将Excel导入数据库及数据库数据导出至Excel的方法
2015/06/24 PHP
使用PHP如何实现高效安全的ftp服务器(二)
2015/12/30 PHP
php遍历解析xml字符串的方法
2016/05/05 PHP
THinkPHP获取客户端IP与IP地址查询的方法
2016/11/14 PHP
Thinkphp整合微信支付功能
2016/12/14 PHP
laravel 错误处理,接口错误返回json代码
2019/10/25 PHP
从数据结构分析看:用for each...in 比 for...in 要快些
2013/04/17 Javascript
JQuery AJAX 中文乱码问题解决
2013/06/05 Javascript
javascript框架设计读书笔记之模块加载系统
2014/12/02 Javascript
JQuery删除DOM节点的方法
2015/06/11 Javascript
基于JavaScript实现移动端TAB触屏切换效果
2015/10/20 Javascript
JavaScript中的定时器之Item23的合理使用
2015/10/30 Javascript
Bootstrap模态对话框的简单使用
2016/04/29 Javascript
分享一个精简的vue.js 图片lazyload插件实例
2017/03/13 Javascript
bootstrap 点击空白处popover弹出框隐藏实例
2018/01/24 Javascript
nodejs 简单实现动态html的方法
2018/05/12 NodeJs
几个你不知道的技巧助你写出更优雅的vue.js代码
2018/06/11 Javascript
vuex actions传递多参数的处理方法
2018/09/18 Javascript
react 生命周期实例分析
2020/05/18 Javascript
实践Python的爬虫框架Scrapy来抓取豆瓣电影TOP250
2016/01/20 Python
python unittest实现api自动化测试
2018/04/04 Python
python 日志增量抓取实现方法
2018/04/28 Python
使用pandas实现csv/excel sheet互相转换的方法
2018/12/10 Python
Win10下python 2.7与python 3.7双环境安装教程图解
2019/10/12 Python
jupyter修改文件名方式(TensorFlow)
2020/04/21 Python
使用纯HTML5编写一款网页上的时钟的代码分享
2015/11/16 HTML / CSS
NFL墨西哥官方商店:Tienda NFL
2017/11/28 全球购物
澳大利亚在线奢侈品时尚零售平台:Azura Runway
2021/01/13 全球购物
小学生成长感言
2014/01/30 职场文书
《只有一个地球》教学反思
2014/02/14 职场文书
会计岗位描述
2014/02/22 职场文书
毕业生就业推荐表自我评价
2015/03/02 职场文书