python中os.path.isdir()和os.path.isfile()的正确用法
生活随笔
收集整理的這篇文章主要介紹了
python中os.path.isdir()和os.path.isfile()的正确用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
之前網上查找os.path.isdir()和os.path.isfile()的使用;發現很多是錯誤的,主要原因是,傳入的參數不是絕對路徑。
先介紹一下os.listdir()方法,此方法返回一個列表,其中包含有指定路徑下的目錄和文件的名稱
import os dirct = '/home/workespace/notebook/' for i in os.listdir(dirct):print(i)redis study_test.ipynb mnist_dataset .ipynb_checkpoints yaml-tool sweetwater makeyourownneuralnetwork Untitled.ipynb AI-Practice-Tensorflow-Notes working cornfieldos.path.isdir()和os.path.isfile()需要傳入的參數是絕對路徑,但是os.listdir()返回的只是一個某個路徑下的文件和列表的名稱.
-
常見錯誤:直接使用os.listdir()的返回值當做os.path.isdir()和os.path.isfile()的入參
-
正確用法:需要先使用python路徑拼接os.path.join()函數,將os.listdir()返回的名稱拼接成文件或目錄的絕對路徑再傳入os.path.isdir()和os.path.isfile().
os.path.join()用法:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os dirct = '/home/workespace/notebook/' for i in os.listdir(dirct):fulldirct = os.path.join(dirct,i)print(fulldirct)/home/workespace/notebook/redis /home/workespace/notebook/study_test.ipynb /home/workespace/notebook/mnist_dataset /home/workespace/notebook/.ipynb_checkpoints /home/workespace/notebook/yaml-tool /home/workespace/notebook/sweetwater /home/workespace/notebook/makeyourownneuralnetwork /home/workespace/notebook/Untitled.ipynb /home/workespace/notebook/AI-Practice-Tensorflow-Notes /home/workespace/notebook/working /home/workespace/notebook/cornfieldos.path.isdir()用于判斷某一對象(需提供絕對路徑)是否為目錄
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os dirct = '/home/workespace/notebook/' for i in os.listdir(dirct):fulldirct = os.path.join(dirct, i)if os.path.isdir(fulldirct): #入參需要是絕對路徑print(i)redis mnist_dataset .ipynb_checkpoints yaml-tool sweetwater makeyourownneuralnetwork AI-Practice-Tensorflow-Notes working cornfieldos.path.isfile()用于判斷某一對象(需提供絕對路徑)是否為文件
import os dirct = '/home/workespace/notebook/' for i in os.listdir(dirct):fulldirct = os.path.join(dirct, i)if os.path.isfile(fulldirct): #入參需要是絕對路徑print(i)study_test.ipynb Untitled.ipynb總結
以上是生活随笔為你收集整理的python中os.path.isdir()和os.path.isfile()的正确用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python的深copy和浅copy
- 下一篇: python中怎么取两个列表 集合的交集