3.2目錄操作(files)
Python os模塊提供了一個統一的操作系統接口函數,這些接口函數通常是平台指定的,os模塊能在不同操作系統平台(如nt或posix)中的特定函數間自動切換,從而能實現跨平台操作。
3.2.1獲取當前工作目錄
os.getcwd():獲取當前工作目錄,即當前Python腳本工作的目錄路徑
>>> import os
>>> os.getcwd()
'D:\\python'
>>>
3.2.2改變當前工作目錄
os.chdir():改變當前腳本工作目錄,相當於shell下的cd命令
>>> import os
>>> os.getcwd()
'D:\\python'
>>> os.chdir("c:\\users")
>>> os.getcwd()
'c:\\users'
>>>
3.2.3 os.curdir/os.pardir/os.name
os.curdir:os.curdir==”.”
os.pardir: os.pardir==”..”,返回當前目錄的父目錄,也就是上一級目錄”..”
os.name:獲取當前使用的操作系統類型(其中”nt”是windows,”posix”是linux或者unix)
>>> import os
>>> os.curdir=="."
True
>>> os.pardir==".."
True
>>>>>> os.getcwd()
'c:\\users'
>>> os.chdir(os.pardir) #相當於os.chdir(“..”)
>>> os.getcwd()
'c:\\'
>>> os.name
'nt'
>>>
3.2.4創建目錄
os.mkdir(path[,mode=0777]):生產單級目錄;相當於linux中的mkdir dirname.參數mode表示生成目錄的權限,默認是超級權限,也就是0777
>>> import os
>>> os.mkdir("d:\\newpath") #在d盤下生成一個名為newpath的目錄
>>> os.mkdir("d:\\newpath") #如果目錄已經存在,會報錯
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 183] : 'd:\\newpath'
>>>
os.makedirs(path[,mode=0777]):可生成多層遞歸目錄,父目錄如果不存在,遞歸生成。.參數mode表示生成目錄的權限,默認是超級權限,也就是0777
>>> import os
>>> os.makedirs("d:\\newpath\\test") #在d盤下生成newpath目錄,並在目錄下新建test目錄
>>> os.makedirs("d:\\newpath\\test") #如果目錄已經存在,會報錯
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\os.py", line 157, in makedirs
mkdir(name, mode)
WindowsError: [Error 183] : 'd:\\newpath\\test'
>>>
3.2.5刪除目錄
os.rmdir(path):刪除單級空目錄,若目錄不為空則無法刪除並保錯,目錄不存在也會報錯;相當於linux中的rmdir dirname.
>>> import os
>>> os.rmdir("d:\\newp") #刪除d盤下newp目錄
>>> os.rmdir("d:\\newp")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 2] : 'd:\\newp'
>>>
os.removedirs(path):若目錄為空,則刪除,並遞歸到上一句目錄,若也為空,則刪除,依次類推。
>>> import os
>>> os.removedirs("d:\\newpath\\test") #成功刪除newpath和test目錄
>>>
3.2.6列表輸出目錄
os.listdir(path):列出指定目錄下的所有文件和子目錄,包括隱藏文件或目錄,並以列表形式返回
>>> import os
>>> os.listdir("d:\\python")[0:4] #輸出目錄下前4個文件或者子目錄
['11.py', '1220test.py', '20180110test.py', 'a.txt']
>>>
3.2.7重命名文件/目錄
os.rename(oldname,newname):重命名文件/目錄
>>> import os
>>> os.rename("d:\\b.txt","d:\\btest.txt") #b.txt文件被命名為btest.txt
>>>
3.2.8獲取文件/目錄信息
os.stat(filename):以元組的形式返回文件/目錄的相關系統信息
>>>import os
>>> os.stat("d:\\python")
nt.stat_result(st_mode=16895, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid
=0, st_size=8192L, st_atime=1516259385L, st_mtime=1516259385L, st_ctime=15014653
79L)
>>>
3.2.9修改文件時間屬性
os.utime(path,(atime,mtime)):修改文件的時間屬性,設置文件的access and modified time(訪問和修改時間)為給定的時間
>>> import os
>>> os.utime("d:\\newfile.txt",(1375448978,1369735977))
>>> os.stat("d:\\newfile.txt")
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid
=0, st_size=48L, st_atime=1375448978L, st_mtime=1369735977L, st_ctime=1516071060
L)
>>>
3.2.10運行shell命令
os.system(command):運行shell命令,可以在python的編譯環境下運行shell的command命令
>>> import os
>>> os.system("dir d:\\python*.*")
驅動器 D 中的卷沒有標簽。
卷的序列號是 A4D1-474C
d:\ 的目錄
2018/01/18 15:09 <DIR> python
0 個文件 0 字節
1 個目錄 160,629,645,312 可用字節
0
>>>
3.2.11創建臨時文件
os.tmpfile():以”w+b”(二進制覆蓋式讀寫)的模式創建並打開一個臨時文件
>>> import os
>>> file=os.tmpfile()
>>> file.write("hi\n")
>>> file.write("hello\n")
>>> file.seek(0,0)
>>> for i in file:
... print i
...
hi
hello
>>> print file
<open file '<tmpfile>', mode 'w+b' at 0x0000000002763150>
>>> file.close()
>>>
3.2.12獲取當前操作系統相關字符或者數據
os.sep:輸出操作系統的特定路徑分隔符;win下為”\”,Linux下為”/”
os.pathsep:輸出用於分割文件路徑的字符串
os.linesep:輸出當前平台使用的行終止符,win下為”\r\n”,Linux下為”\n”,Mac使用”\r”.
os.environ:獲取系統環境變量,以字典的格式輸出
>>> import os
>>> os.sep
'\\'
>>> os.pathsep
';'
>>> os.linesep
'\r\n'
>>> os.environ
{'TMP': 'C:\\Users\\pangwei\\AppData\\Local\\Temp'}
3.2.13文件操作權限
os.access(path,mode):輸出文件權限模式;W寫,R讀,X可執行,輸出True or Fasle
>>> import os
>>> os.access("d:\\newfile.txt",os.W_OK) #判斷當前是否擁有文件的寫權限
True
>>> os.access("d:\\newfile.txt",os.R_OK)
True
>>> os.access("d:\\newfile.txt",os.X_OK)
True
>>>
os.chmod(path,mode):修改文件的權限
>>> import os
>>> os.chmod("d:\\newfile.txt",0777) #修改文件權限為超級權限(0777),可讀可寫可執行
>>>
3.2.14文件遍歷os.walk()
os.walk(top,topdown=True,onerror=None,followlinks=False):此函數返回一個列表,列表中的每一個元素都是一個元組,該元組有三個元素,分別表示每次遍歷的路徑名(root),目錄列表(dirs)和文件列表(files),一般使用格式為:
for root,dirs,files in os.walk(path,topdown=False):
….
參數說明:
top:表示要遍歷的目錄樹的路徑
topdown:表示首先返回目錄樹下的文件,然后遍歷目錄樹下的子目錄,默認值為True。值設置為False時,表示先遍歷目錄樹下的子目錄,返回子目錄下的文件,最后返回根目錄下的文件。
onerror:默認值是None,表示忽略文件遍歷時產生的錯誤,如果不為空,則提供一個自定義的函數提示錯誤信息后繼續遍歷或者拋出異常終止遍歷。
followlinks:默認情況下,os.walk不會遍歷軟鏈接指向的子目錄,若有需要可以將followlinks設定為True
3.2.15路徑操作方法(os.path模塊)
os.path.dirname(path):os.path模塊中的方法,返回path的目錄路徑,也就是os.path.split(path)的第一個元素。
os.path.basename(path):返回path最后的文件名,如果path以/或者\結尾,就會返回空值,也就是os.path.split(path)的第二個元素
os.path.exists(path):判斷目錄或者文件是否存在,如果存在返回True,否則返回False。
>>> import os.path
>>> os.path.exists("d:\\newfile.txt")
True
>>>
os.path.isabs(path):判斷path是否是絕對路徑,如果是返回True,否則返回False。
>>> import os.path
>>> os.path.isabs("d:\\newfile.txt")
True
>>>
os.path.isfile(path):判斷path是否是文件,如果是返回True,否則返回False。
>>> import os.path
>>> os.path.isfile("d:\\newfile.txt")
True
>>>
os.path.isdir(path):判斷path是否是目錄,如果是返回True,否則返回False。
>>> import os.path
>>> os.path.isdir("d:\\newfile.txt")
False
>>>
os.path.getsize(name):獲得文件大小,如果name是目錄返回0L,如果name代表的目錄或者文件不存在,則會報WindowsError異常
>>>import os.path
>>> os.path.getsize("d:\\newfile.txt")
48L
>>>
os.path.join(a,*p):連接兩個或更多的路徑名,中間以”\”分隔,如果所給的參數中都是絕對路徑名,那只保留最后的路徑,先給的將會被弄丟
>>> import os.path
>>> os.path.join("d:\\aa","test","a.txt")
'd:\\aa\\test\\a.txt'
>>> os.path.join("d:\\aa","d:\\test","d:\\a.txt")
'd:\\a.txt'
>>>
os.path.splitext (path):分離文件名和擴展名
>>>import os
>>> os.path.splitext("d:\\stdout.txt")
('d:\\stdout', '.txt')
>>>
os.path.splitdrive (path):拆分驅動器和文件路徑,並以元組返回結果,主要對win有效,Linux元組第一個總是空。
>>> os.path.splitdrive("d:\\stdout.txt")
('d:', '\\stdout.txt')
>>>
os.path.getatime (file_name):返回文件最后的存取時間,返回的是時間戳,可以引入time包對時間進行處理
>>> import os
>>> import time
>>> Lasttime=os.path.getatime("d:\\stdout.txt") #獲取文件最后存取時間
>>> print Lasttime
1516608557.96
>>> formattime=time.localtime(Lasttime) #將時間戳轉成時間元組
>>> print formattime
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=22, tm_hour=16, tm_min=9, tm_se
c=17, tm_wday=0, tm_yday=22, tm_isdst=0)
>>> print time.strftime("%Y-%m-%d %H:%M:%S",formattime) #格式化時間元組為時間字符串
2018-01-22 16:09:17
>>>
os.path.getctime (file_name):返回文件或者目錄的創建時間,返回的是時間戳,在Unix系統上是文件最近的更改時間,在Win上是文件或者目錄的創建時間
>>> import os
>>> import time
>>> lastTime=os.path.getctime("d:\\stdout.txt") #獲取文件的創建時間
>>> print lastTime
1516608557.96
>>> FormatTime=time.localtime(lastTime) #將時間戳轉換為時間元組
>>> print FormatTime
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=22, tm_hour=16, tm_min=9, tm_se
c=17, tm_wday=0, tm_yday=22, tm_isdst=0)
>>> print time.strftime("%Y-%m-%d %H:%M:%S",FormatTime) #格式化時間戳
2018-01-22 16:09:17
>>>
os.path.getmtime (file_name):獲取文件最后的存取時間
os.path.walk (top,func,arg):遍歷目錄路徑:
top:表示需要遍歷的目錄樹的路徑;
func表示回調函數,對遍歷路徑進行處理的函數。所謂回調函數,是作為某個函數的的參數使用,當某個時間觸發時,程序將調用定義好的回調函數處理某個任務。該回調函數必須提供3個參數:第
1個參數為walk()的參數arg,第2個參數表示目錄列表dirname
,第3個參數表示文件列表names。
arg:是傳遞給回調函數func的元組,為回調函數提供處理參數,回調函數的第一個參數就是用來接收這個傳入的元組的,參數arg可以為空。
#coding=utf-8
import os
#回調函數
def find_file(arg, dirname, files):
#for i in arg:
#print i
for file in files:
file_path = os.path.join(dirname, file)
if os.path.isfile(file_path):
print "file:%s" %file_path
#調用
os.path.walk(r"d:\python", find_file, (1,2))
