zoukankan      html  css  js  c++  java
  • python_os

    1. 基本功能的介绍

        os模块包含普通的操作系统的功能

    2. 常用的变量

    (1)os.name

    获取正在使用的平台, Windows 返回 nt, Linux或者Unix 返回 posix

    3. 常用的方法

    (1)getcwd

    string = os.getcwd()

    获取当前工作目录

    (2)getenv

    string = os.getenv(varname[, value])

    获取环境变量的值,如果环境变量的值不存在,则返回None

    (3)listdir

    list = os.istdir(path)

    获取指定路径下的所有目录和文件

    (4)remove

    os.remove(path)

    删除指定的文件,如何文件不存在,系统报OSError

    (5)split

    元组 = os.path.split(path)

    返回一个路径的目录名和文件名

    (6)join

    string = os.path.join(path1[, path2[, ...]])

    将目录和文件组合成路径

    (7)exists

    string = os.path.exists(path)

    判断路径是否存在,存在则返回True,不存在,则返回False

    (8)isdir

    string = os.path.isdir(path)

    判断路径是否为目录,如果是,则返回True;否则,则返回False

    (9)isfile

    string = os.path.isfile(path)

    判断路径是否为文件,如果是,则返回True;否则,则返回False

    (4)walk(暂无示例)

    root, dirs, files = os.walk(top, topdown=True, onerror=None, followlinks=False)

    获取一个目录下面的所有路径、目录名、文件名

    topdown= True: 代表从上到下遍历,或者说从根遍历到叶子

    topdown= False: 代表从下到上遍历,或者说从叶子遍历到根

     

      4. 示例

    #-*- coding:utf-8 -*-
    
    import os
    
    #获取正在使用的平台, Windows 返回 nt, Linux或者Unix 返回 posix
    print os.name
    
    #获取当前工作目录
    print os.getcwd()
    
    #获取环境变量
    print os.getenv("JAVA_HOME")
    
    #获取指定目录下,所有文件和文件名
    print os.listdir("E:python_script")
    
    #删除指定的文件
    try:
        os.remove("E:/python_script/test.txt")
    except:
        print "文件已经被删除"
    else:
        print "删除文件成功"
    
    print os.listdir("E:python_script")
    
    #返回一个路径的目录名和文件名
    print os.path.split("E:/python_script/hello.py")
    
    #将目录和文件名组合成路径
    print os.path.join("E:python_script", "test.txt")
    
    #判断一个路径是否真的存在
    print os.path.exists("E:/python_script/hello.py")
    
    #判断一个路径是否为目录
    print os.path.isdir("E:/python_script/hello.py")
    
    #判断一个路径是否为文件
    print os.path.isfile("E:/python_script/hello.py")

    5. 运行结果

  • 相关阅读:
    P4315 月下“毛景树”
    P1505 [国家集训队]旅游
    P3258 [JLOI2014]松鼠的新家
    P4116 Qtree3
    P2580 于是他错误的点名开始了
    P3038 [USACO11DEC]牧草种植Grass Planting
    P3128 [USACO15DEC]最大流Max Flow
    P2146 [NOI2015]软件包管理器
    P2590 [ZJOI2008]树的统计
    P3384 【模板】树链剖分
  • 原文地址:https://www.cnblogs.com/zhuhaiying/p/6138816.html
Copyright © 2011-2022 走看看