zoukankan      html  css  js  c++  java
  • python中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()用法:

    #Python学习交流群:778463939
    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()用于判断某一对象(需提供绝对路径)是否为目录

    #Python学习交流群:778463939
    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
    
  • 相关阅读:
    SP笔记:交叉实现七行并成一行
    HTML tag 学习
    操作哈希表
    Efficient bipedal robots based on passivedynamic walkers
    Pushing People Around
    ZEROMOMENT PONTTHIRTY FIVE YEARS OF ITS LIFE

    Active Learning for RealTime Motion Controllers
    Accelerometerbased User Interfaces for the Control of a Physically Simulated Character
    Dynamic Response for Motion Capture Animation
  • 原文地址:https://www.cnblogs.com/xxpythonxx/p/13805635.html
Copyright © 2011-2022 走看看