Python_OS模塊

一. os模塊
1.os.access()
查看文件是否有指定權限,結果爲True或False
os.access(path, mode)
path:指定文件路徑
mode:判定依據 (F_OK(是否存在),R_OF(是否可讀),W_OK(是否可寫),X_OK(是否可執行))

>>> os.access('/python/a.py',os.F_OK)  #是否存在
True
>>> os.access('/python/a.py',os.R_OK)  #是否可讀
True
>>> os.access('/python/a.py',os.W_OK)  #是否可寫
True
>>> os.access('/python/a.py',os.X_OK)  #是否可執行
False

2.os.chdir()
用於更改當前工作目錄到指定的路徑

>>> os.getcwd()   #查看當前工作路徑
'/python
>>> os.chdir('/sulong/test/')  #修改當前工作路徑到‘/sulong/test/’
>>> os.getcwd()
'/sulong/test'

3.os其他常用命令

>>> os.name #判斷現在的實用平臺,windows返回‘nt’,linux返回
'posix'
>>> os.getcwd() #返回當前工作的目錄
'/root'
>>> os.listdir('.') #返回指定目錄下所有的文件和目錄名
['file.txt', 'test', 'caidan.py', 'test.txt', 'test.py', 'test1.py', 'enumerate.py', 'login.py']
>>> os.remove('test1.py') #刪除指定文件
>>> os.listdir('.')
['file.txt', 'test', 'caidan.py', 'test.txt', 'test.py', 'enumerate.py', 'login.py']
>>> os.rmdir('aaa')  #刪除指定目錄
>>> os.mkdir('directory')  #創建目錄,只能創建一層目錄
>>>os.path.isfile()——判斷指定對象是否爲文件。是返回True,否則False
>>> os.path.isfile('test.py')  #爲文件返回True
True
>>> os.path.isfile('directory') #此爲目錄則返回false
False
>>> os.path.isdir('directory')  #判斷指定對象是否爲目錄。
True
>>> os.path.exists('/python/test.py') #判斷指定的對象是否存在
True
>>> os.path.exists('/python/caidan')
False
>>> os.path.split('/python/test.py') #返回路徑的目錄和文件名
('/python', 'test.py')
>>> os.getcwd()  #獲取當前工作的目錄
'/python'
>>> os.system('pwd')  #執行shell命令
/python
>>> os.system("echo 'hello world!'")
hello world!
>>> os.path.getsize('directory') #獲得文件的大小,如果爲目錄返回0
>>> os.path.abspath('.') #獲得絕對路徑
'/python'
>>> os.path.join('/python/directory/','test.py') #鏈接目錄和文件名
'/python/directory/test.py'
>>> os.path.basename('/python/directory/test.py') #返回文件名
'test.py'
>>> os.path.basename('/python/directory')
'directory'
>>> os.path.dirname('/root/directory/test.py') #返回文件路徑
'/root/directory'
>>> os.path.getmtime('.') #返回在此path下最後一次修改的時間戳
1510553280.2887046
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章