【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)
原文地址:https://www.cnblogs.com/utank/p/10617561.html