码迷,mamicode.com
首页 > 编程语言 > 详细

python中os.path.isdir()和os.path.isfile()的正确用法

时间:2018-11-02 14:30:42      阅读:1253      评论:0      收藏:0      [点我收藏+]

标签:返回值   需要   名称   python   ase   key   book   判断   一个   

之前网上查找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
cornfield

os.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()用法:

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/cornfield

os.path.isdir()用于判断某一对象(需提供绝对路径)是否为目录

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
cornfield

os.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   ase   key   book   判断   一个   

原文地址:https://www.cnblogs.com/forsch/p/9895606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!