用python批量刪掉文件名中共同存在的字符


小木蟲是一個很好的網站,上面有很多學習資料,但是從小木蟲上下載的資料的文件名前面會有"[muchong.com]"這個字符存在,

有時候資料下載多了一個個重命名很麻煩,所以從網上學習自己寫了一個python小程序用來批量刪掉這個字符

import os

def batchrename(path):
    os.chdir(path)
    print("   CHANGE DIRECTORY TO THE PATH   ")
    filelist = os.listdir(path)
    print("   File List   ")
    for filename in filelist:
        print(filename)
        if "muchong.com" in filename:
            print("-----------------------This one needs renamed")
            pos = filename.find("]")
            newname = filename[pos+1:]
            os.rename(filename,newname)
  
batchrename("C:\Users\zhanchao\Downloads")

 

 

參考網頁:

http://www.51ou.com/browse/python/43910.html

http://www.cnblogs.com/pzxbc/archive/2012/03/17/2404060.html

 

自己運行時出現錯誤windowsError183,折騰了一下才發現是因為之前下載了同一本書,所以出錯。

 

----------------------------------------------------------------------2017年7月1日更新------------------------------------------

當然也可以先在cmd里手動改變路徑(一般是cd C:\Users\username\Downloads),然后再運行下面腳本

 1 import os
 2 
 3 def batchrename():
 4     filelist = os.listdir()
 5     print("   File List   ")
 6     for filename in filelist:
 7         print(filename)
 8         if "muchong.com" in filename:
 9             print("-----------------------This one needs renamed")
10             pos = filename.find("]")
11             newname = filename[pos+1:]
12             os.rename(filename,newname)
13             
14 batchrename()

因為重裝系統后發現上面的腳本出錯,不能讀路徑,不知道為什么,所以只好先在cmd里改。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM