• 技术文章 >后端开发 >Python教程

    Python 文件重命名工具代码

    2016-06-06 11:26:55原创423
    代码如下:


    #Filename:brn.py
    #Description: batch replace certain words in file names
    #Use to bat rename the file in a dir(modify the suffix from a to b) for Windows Vista OS
    import sys
    import os
    import fnmatch
    import re
    #parse params
    p=input("Please input work directory(current path for enter):")
    if p=='\r':
    p='.'
    p=p.rstrip('\r')
    print (p)
    while not os.path.exists(p):
    print (p+' is not existed.Please input the work directory:')
    p=input("Please input work directory(current path for enter):")
    s=input("Please enter the words which need be modified(must):")
    while s=='\r':
    s=input("Please enter the words which need be replaced(must):")
    s=s.rstrip('\r')
    d=input("Please enter the words which want to change to(must):")
    while d=='\r':
    d=input("Please enter the words which want to change to(must):")
    d=d.rstrip('\r')
    try:
    sure=input("Are you sure to rename the file named *"+s+"*"+" to *"+d+"*"+" in directory "+p+"? y/n:")
    sure=sure.rstrip('\r')
    if sure!='y':
    print ("Cancel")
    else:
    for root, dirs, files in os.walk(p, True):
    for file in files:
    print (os.path.join(root,file))
    if os.path.isfile(os.path.join(root,file)):#Only file is file,not a dir ,do this
    if fnmatch.fnmatch(file, '*'+s+'*'):
    f=str(file).replace(s,d)
    if p=='.':
    command='move '+str(file)+" "+f
    else:
    command="move "+os.path.join(root,file)+" "+os.path.join(root,f)
    print (command)
    if os.system(command)==0:#do actual rename
    print ("Rename "+str(file)+" to "+f+" success")
    else:
    print ("Rename "+str(file)+" to "+f+" failed")
    #else:
    #print str(file)+" is a directory.omit"
    except IndexError:
    print (IndexError.message)

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:Python 文件重命名
    上一篇:python 提取文件的小程序 下一篇:python thread 并发且顺序运行示例

    相关文章推荐

    • 一文了解Python中如何使用query()进行优雅的查询• 举例讲解Python设计模式编程中对抽象工厂模式的运用• 跟老齐学Python之永远强大的函数• Python使用urllib2模块抓取HTML页面资源的实例分享• Python的Flask开发框架简单上手笔记

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网