OS Module
Gives us the ability to write Python codes compatible with any operating system
- Linux/UNIX
- use / to separate directory
- only one root directory
- File system : ext4 (Fourth extended filesystem)
- macOS
- use / to separate directory
- only one root directory
- File system : APFS (Apple Filesystem)
- Windows
- use \ to separate directory
- there are A:\, C:\ OR D:\. (The C drive is usually where OS is located in.)
- File system : NTFS (New Technology Filesystem)
Functions
- os.getcwd() returns a string representing the current working directory.
- os.listdir(path=‘.’) returns a list containing the names of the entries in the directory given by path. Notice that the default argument of os.listdir() is a dot. In both Windows and Linux/UNIX, a dot represents the current directory.
- os.curdir – is a constant representing the current directory. For example, it is "." on Linux, Windows, and OS X. It is, however, ":" on old Mac OS 9 systems.
- os.pardir – is a constant representing the parent directory.
- os.path.join(path1, path2) – Join one or more path components intelligently. It make code portable, smart and clear.
import os
print(os.getcwd()) #/Users/hannah/Desktop/python code
print(os.listdir()) #['try.py', 'hello.txt']
print(os.curdir) #.
print(os.listdir(os.curdir)) #['try.py', 'hello.txt']
print(os.pardir) #..
print(os.listdir(os.pardir)) #['python code']
print(os.path.join('python code','try.py')) #python code/try.py
ps. 以上為mac的示範
- os.path.split(path) : 返回(路徑,檔名)
- os.path.basename(path) : 返回檔案名稱
- os.path.dirname(path) : 返回路徑
- os.path.splitext(path) : 返回(路徑/檔案名稱,副檔名)
- os.path.abspath(filename) : 返回絕對路徑
import os
#filepath = 'whatever\\\\some\\\\directory\\\\path.jpg' #win
filepath = 'whatever/some/directory/path.jpg' #mac
print(os.path.split(filepath)) #('whatever/some/directory', 'path.jpg')
print(os.path.basename(filepath)) #path.jpg
print(os.path.dirname(filepath)) #whatever/some/directory
print(os.path.splitext(filepath)) #('whatever/some/directory/path', 'jpg')
print(os.path.*abspath*(filepath)) #/Users/hannah/Desktop/python code/whatever/some/directory/path.jpg
- os.path.exists(path) : 檢驗路徑是否存在 返回bool
- os.path.isdir(path) : 判斷是否為目錄 返回bool