Python OS模塊重要知識點
Python OS模塊重要知識點
這幾點很重要,主要是關於文件路徑,我之前踩了很多坑,今天總結一下,方便以後能夠避免與path相關的各種坑!
1,首先我們想獲取某個文件夾下面的所有文件夾以及文件(不包括子文件夾裏面的文件)
lists = os.listdir( Path )
2,想獲取某個文件夾(Path )下面的所有文件夾以及文件(包括子文件夾裏面的文件)
def listDir( path ): for filename in os.listdir(path): pathname = os.path.join(path, filename)if (os.path.isfile(filename)): print pathname else: listDir(pathname)
3,獲取上級目錄文件夾:
C:\test getpath.py
\sub sub_path.py
比如在 sub_path.py 文件裏面的這一句代碼 os.path.abspath(os.path.dirname(__file__)) 可以獲取 \sub\ 目錄的絕對路徑
比如在 sub_path.py 文件裏面的這一句代碼 os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
4,獲取當前目錄及上級目錄
└── folder
├── data
│ └── data.txt
└── test
└── test.py
print ‘***獲取當前目錄***‘ print os.getcwd() print os.path.abspath(os.path.dirname(__file__)) print ‘***獲取上級目錄***‘ print os.path.abspath(os.path.dirname(os.path.dirname(__file__))) print os.path.abspath(os.path.dirname(os.getcwd()))print os.path.abspath(os.path.join(os.getcwd(), "..")) print ‘***獲取上上級目錄***‘ print os.path.abspath(os.path.join(os.getcwd(), "../..")) ***獲取當前目錄*** /workspace/demo/folder/test /workspace/demo/folder/test ***獲取上級目錄*** /workspace/demo/folder /workspace/demo/folder /workspace/demo/folder ***獲取上上級目錄*** /workspace/demo
此外:
#curdir 表示當前文件夾 print(os.curdir) #pardir 表示上一層文件夾 print(os.pardir)
5,調用其他目錄的文件時,如何獲取被調用文件的路徑
C:\test getpath.py
\sub sub_path.py
比如C:\test目錄下還有一個名為sub的目錄;C:\test目錄下有getpath.py,sub目錄下有sub_path.py,getpath.py調用sub_path.py;我們在C:\test下執行getpath.py。
如果我們在sub_path.py裏面使用sys.path[0],那麽其實得到的是getpath.py所在的目錄路徑“C:\test”,因為Python虛擬機是從getpath.py開始執行的。
如果想得到sub_path.py的路徑,那麽得這樣:
os.path.split(os.path.realpath(__file__))[0]
其中__file__雖然是所在.py文件的完整路徑,但是這個變量有時候返回相對路徑,有時候返回絕對路徑,因此還要用os.path.realpath()函數來處理一下。
也即在這個例子裏,os.path.realpath(__file__)輸出是“C:\test\sub\sub_path.py”,而os.path.split(os.path.realpath(__file__))[0]輸出才是“C:\test\sub”。
總之,舉例來講,os.getcwd()、sys.path[0] (sys.argv[0])和__file__的區別是這樣的:
假設目錄結構是:
C:\test | [dir] getpath | [file] path.py [dir] sub | [file] sub_path.py
然後我們在C:\test下面執行python getpath/path.py,這時sub_path.py裏面與各種用法對應的值其實是:
os.getcwd() “C:\test”,取的是起始執行目錄
sys.path[0]或sys.argv[0] “C:\test\getpath”,取的是被初始執行的腳本的所在目錄
os.path.split(os.path.realpath(__file__))[0] “C:\test\getpath\sub”,取的是__file__所在文件sub_path.py的所在目錄
Python OS模塊重要知識點