zoukankan      html  css  js  c++  java
  • 【Python】批量修改指定目录下所有文件的文件名/后缀

    【删除.txt文件的后缀】

    import os, shutil
    
    #rootdir = input("请输入文件路径(结尾加上/):")
    
    #fileList = os.listdir(rootdir)
    
    #修改文件名
    def renameFile( oldname, newname ):
        print( "oldname:", oldname )
        print( "newname:", newname )
        #os.rename(oldname, newname)
        shutil.copyfile( oldname, newname)
        
    #列出txt文件
    def listTxtFile( filepath ):
        if os.path.isfile(filepath) and ".txt" == filepath[-4:] :
            oldName = filepath
            newName = oldName[:-4]
            #print("oldName:", oldName)
            #print("newNmae:", newName)
            #os.rename(oldName, newName)
            #shutil.copyfile(oldName, newName)
            renameFile( oldName, newName )
            
    #遍历目录下所有的文件
    def listPath( filepath ):
        fileList = os.listdir( filepath )
        for fi in fileList:
            fi_d = os.path.join( filepath, fi )
            if os.path.isdir( fi_d ):
                listPath(fi_d)
            else:
                listTxtFile(fi_d)
    
    """
    for i in range(0, len(fileList)):
        path = os.path.join(rootdir, fileList[i])
        if os.path.isfile(path) and ".txt" == fileList[i][-4:] :
            oldName = path
            newName = oldName[:-4]
            print("oldName:", oldName)
            print("newNmae:", newName)
            #os.rename(oldName, newName)
            #shutil.copyfile(oldName, newName)
    """
    
    if __name__ == "__main__":
        rootdir = input("请输入文件路径(结尾加上/):")
        listPath(rootdir)
  • 相关阅读:
    [硬件驱动_蓝牙]蓝牙Bluez的编程实现
    二分查找
    LeetCode-35.Search Insert Position
    LeetCode-34.Find First and Last Position of Element in Sorted Array
    LeetCode-704.Binary Search
    剑指offer-最小的k个数
    树的各种遍历
    LeetCode-912.Sort an Array
    排序
    LeetCode-209.Minimum Size Subarray Sum
  • 原文地址:https://www.cnblogs.com/utank/p/10617561.html
Copyright © 2011-2022 走看看