1. 程式人生 > >Python入門:os部分方法介紹(一)

Python入門:os部分方法介紹(一)

>>> help(os)

Help on module os:

NAME
os - OS routines for Mac, NT, or Posix depending on what system we’re on.
os顧名思義就是有關作業系統的相關操作

#cwd = Current Working Directory(當前工作目錄)
>>> help(os.getcwd)
Help on built-in function getcwd in module posix:

getcwd(...)
    getcwd() -> path

    Return a string representing the current working directory.
>>> os.getcwd()
'/Users/frankslg/PycharmProjects/untitled'
>>> help(os.listdir)
Help on built-in function listdir in module posix:

listdir(...)
    listdir(path) -> list_of_strings
    #需要傳入一個引數‘path’,這個path就可以是從別的地方傳入的,也可以是自己寫的,當然也可以是當前檔案所在的目錄
    Return a list containing the
names of the entries in the directory. #返回一個列表包含傳入的目錄名中的所有內容 path: path of directory to list The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory. #這個列表是任意順序的。它不包括特殊‘.’和‘..’,即使存在當前目錄中
>>> os
.listdir(os.getcwd()) ['.idea', 'test.py', 'test1.py']

以上兩個方法特別有用,在很多場合都可以使用,比如:需要列出當前檔案所在目錄的所有檔案怎麼辦?列出所有檔案能幹什麼?可以做檔案查詢指令碼!!!可以新建檔案、刪除檔案等等!!!

>>> os.name
'posix'

os.name輸出當前平臺。如果是window 則用’nt’表示,對於Linux/Unix/mac使用者,它是’posix’。

>>> os.listdir(os.getcwd())
['.idea', '123', 'test.py', 'test1.py']
>>> os.remove('123')
#刪除‘123’這個檔案
>>> os.listdir(os.getcwd())
['.idea', 'test.py', 'test1.py']

執行系統命令

>>> os.system('ls')
123
test.py
test1.py
0

系統的路徑分隔符和行終結符。不同系統不一樣,windows是‘\’和‘\r\n’,類unix系統如下:

>>> os.sep
'/'
>>> os.linesep
'\n'

注:這在很多指令碼中都很重要,需要開發一個可移植性的指令碼,就需要判斷這些資訊,以做到不同作業系統的相同處理結果

>>> os.path.split(os.getcwd())
('/Users/frankslg/PycharmProjects', 'untitled')
#返回當前檔案所在的路徑和當前檔名

os.path.isfile #判斷是不是檔案
os.path.isdir #判斷是不是目錄
os.path.exists #判斷存在不存在
……
拼接新的目錄

>>> os.path.join('/tmp/','123')
'/tmp/123'

獲取檔案字尾名

>>> os.path.splitext('/tmp/123.txt')
('/tmp/123', '.txt')
>>> os.path.splitext('123.txt')
('123', '.txt')

等等……!!!