【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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM