zoukankan      html  css  js  c++  java
  • 批量重命名文件——python实现

    任务很简单,某个目录下面有几千个文件,某些文件没有后缀名,现在的任务就是将所有的没有后缀名的文件加上后缀名,python有现成的函数可以实现,但是在实现过程中遇到几个问题,分享一下解决方法

    下面是最终代码 (windows下实现的)

    # -*- coding: cp936 -*-
    import os
    path = 'D:\\图片\\'
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path,file))==True:
            if file.find('.')<0:
                newname=file+'rsfdjndk.jpg'
                os.rename(os.path.join(path,file),os.path.join(path,newname))
                print file,'ok'

    #        print file.split('.')[-1] 

     实现的方法是:首先遍历path指定的目录,如果是文件(不是文件夹)并且文件名中不存在 ‘.’ ,也就是没有后缀名,就把这个文件加上后缀名,然后重命名

    有些细节需要注意:

    1.如果path指定的文件夹不是这个程序的所在的目录,rename函数里面的路径就必须是绝对路径,否则就会报‘WindowsError: [Error 2]’错误

    2.重命名时如果新文件名已经存在,就会报‘WindowsError: [Error 183]’ 错误,所以,新文件名最好加上一些随机字符串

    3.如果改文件名或者后缀名可以用split() 函数进行分割

    4.find函数如果找不到指定的字符串的话就会返回 ‘-1’ 

  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/ma6174/p/2482378.html
Copyright © 2011-2022 走看看