Python模块: 文件和目录os+shutil
一 常用函數(shù)
os模塊
os.sep 表示默認(rèn)的文件路徑分隔符,windows為\, linux為/
os.walk(spath): 用來遍歷目錄下的文件和子目錄
os.listdir(dirname):列出dirname下的目錄和文件
os.mkdir() : 創(chuàng)建目錄
os.makedirs(): 創(chuàng)建目錄,包含中間級目錄
os.remove():刪除文件,不能是目錄
os.rmdir():刪除空目錄
os.removedirs(path):刪除目錄及其子目錄
os.rename(src, dst) :修改文件名
os.renames(old, new) :修改文件或目錄名,包含中間級
os.chdir("/tmp") : 更改當(dāng)前目錄
os.chmod( "c:\\test\\buildid.txt", stat.S_IWRITE ) : 去除文件的只讀屬性
os.path模塊
os.path.pathsep 表示默認(rèn)的路徑間的分隔符,windows為; Linux為:
os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false
os.path.isfile(name):判斷name是不是一個文件,不存在name也返回false
os.path.exists(name):判斷是否存在文件或目錄name
os.path.getsize(name):獲得文件大小,如果name是目錄返回0L
os.path.getctime(name):獲得文件的創(chuàng)建時間
os.path.getmtime(name):獲得文件的修改時間
os.path.getatime(name):獲得文件的最后訪問時間
?
os.path.isabs(name):測試是否是絕對路徑
os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規(guī)范path字符串形式
os.path.relpath(path, start='.'):返回路徑的相對版本
os.path.split(name):分割文件名與目錄(事實上,如果你完全使用目錄,它也會將最后一個目錄作為文件名而分離,同時它不會判斷文件或目錄是否存在)
os.path.splitext():分離文件名與擴(kuò)展名
os.path.splitdrive():分離驅(qū)動名或unc名字
os.path.join(path,name):連接目錄與文件名或目錄
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路徑
shutil模塊
shutil.copyfile(src, dst): 拷貝文件
shutil.copytree(srcDir, dstDir) : 拷貝目錄
shutil.rmtree('dir') : 刪除非空文件夾
shutil.move('old','new') :修改文件和目錄名稱
?
glob模塊
匹配文件:glob.glob(r”c:\linuxany\*.py”)
二 實例 (os.walk的遍歷過程如下)
1 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 2 3 import os 4 5 # tree c:\test /f 6 #C:\TEST 7 #│ test.log 8 #│ 9 #├─test2 10 #│ test2.log 11 #│ 12 #└─test3 13 14 tree = os.walk('C:/test') 15 for directoryItem in tree: 16 directory=directoryItem[0] 17 subDirectories=directoryItem[1] 18 filesInDirectory=directoryItem[2] 19 print('-----------------') 20 print('the directory is :', directory) 21 print('the sub directories are : ', subDirectories) 22 print('the files are :', filesInDirectory) 23 24 #----------------- 25 #the directory is : C:/test 26 #the sub directories are : ['test2', 'test3'] 27 #the files are : ['test.log'] 28 #----------------- 29 #the directory is : C:/test\test2 30 #the sub directories are : [] 31 #the files are : ['test2.log'] 32 #----------------- 33 #the directory is : C:/test\test3 34 #the sub directories are : [] 35 #the files are : []轉(zhuǎn):http://www.cnblogs.com/itech/archive/2009/12/16/1625636.html
總結(jié)
以上是生活随笔為你收集整理的Python模块: 文件和目录os+shutil的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 乐高可能和任天堂合作,推出《塞尔达传说》
- 下一篇: 亚马逊高管解读 Q4 财报:首要任务是降