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
    
  • 相关阅读:
    求文件的hash值(基于SHA3的Hash)
    Discrete Log Algorithms :Baby-step giant-step 【二】
    非专业填坑
    xml转换csv
    使用PowerShell批量注册DLL到GAC
    ui-grid 中cellTemplate中click事件
    ui-grid样式,表格高度自适应行高,没有滚动条,去掉表头
    ui-grid使用详解
    数组过滤重复元素
    正则表达式验证邮箱
  • 原文地址:https://www.cnblogs.com/xxpythonxx/p/13805635.html
Copyright © 2011-2022 走看看