【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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值