處理語料庫時,有些文件名字很不規則,為了方便處理,同義按數字順序修改名稱,主要是用到os模塊:
import os def RenameFiles(srcdir): #將目錄下所有的文件命名為數字開頭的名稱 srcfiles = os.listdir(srcdir) index = 1 for srcfile in srcfiles: print srcfile sufix = os.path.splitext(srcfile)[1] print sufix destfile = srcdir + "//" + u"%d"%(index) + sufix srcfile = os.path.join(srcdir, srcfile) os.rename(srcfile, destfile) index += 1 srcdir = u"奧運" RenameFiles(srcdir)
當然,上述重復運行就出錯,應為rename函數中的兩個參數必須不同名。
附:主要os模塊屬性和方法:
1.os.getcwd()
得到當前py文件所在工作目錄。
2.os.name
得到使用平台的字符串。window ——'nt'表示,Linux/Unix——'posix'。
3.os.listdir('目錄名')
得到目錄下的所有文件和目錄名。
4.os.remove()
刪除當前目錄下的指定文件。(相對路徑)
5.os.system(‘系統命令名稱’)
運行shell命令。
6.os.sep 顯示操作系統特定的路徑分割符。
7.os.linesep 顯示當前平台使用的行終止符
8.os.path.split("文件絕對路徑名稱")
得到文件絕對路徑的目錄名和文件名
9.os.path.isfile()和os.path.isdir()
檢測給出的路徑是文件名還是路徑名稱
10.os.path.exists('路徑名稱')
判斷路徑是否真地存在
11.os.path.abspath("文件名稱")——獲得絕對路徑。常用os.path.abspath(__file__):得到當前腳本所在的絕對路徑。
12.os.path.normpath(path)——獲得規范path的字符串形式
13.os.path.getsize(name):獲得文件大小,如果name是目錄返回0L
14.os.path.splitext():分離文件名與擴展名
15.os.path.join(path,name):連接目錄與文件名或目錄
16.os.path.basename(path):不論絕對路徑還是相對路徑只返回文件名
17.os.path.dirname(path):返回文件絕對路徑