>  기사  >  백엔드 개발  >  Python의 os 모듈

Python의 os 모듈

巴扎黑
巴扎黑원래의
2017-07-24 16:24:161488검색

Python 파일 시스템 기능: os 모듈

1.os 모듈 메서드 분류

(1) 디렉터리:

    chdir()         改变工作目录
    chroot()        设定当前进程的根目录
    listdir()       列出指定目录下的所有文件名
    mkdir()         创建指定目录
    makedirs()      创建多级目录
    getcwd()        返回当前工作目录
    rmdir()         删除指定目录
    removedirs()    删除多级目录

(2) 파일:

    mkinfo()        创建管道
    mknod()         创建设备文件
    remove()        删除文件
    unlink()        删除链接文件
    rename()        重命名
    stat()          返回文件状态信息
    symlink()       创建符号链接
    utime()         更新时间戳
    tmpfile()       创建并打开(w+b)一个新的临时文件

(3) 액세스 권한

    access(path, mode)      判断指定用户是否有访问权限      os.access('/tmp',0)   uid为0用户是否有权限访问/tmp目录
    chmod(path,mode)        修改权限        os.chmod('/tmp/s',0640) 将/tmp/s 权限修改为640
    chown(path,uid,gid)     修改属主、属组  
    umask()                 设置默认权限模式        os.umask(022)

(4) 장치 파일

    makedev()       创建设备
    major()         指定设备获取主设备号
    minor()         指定设备获取次设备号

(5) 파일 설명자

    open()          较低的IO打开
    read()          较低的IO读
    write()         较低的IO写

4、5相对用的少
补充:
    os.walk()   相当于tree命令
    >>> import os
    >>> a1 = os.walk('/root')
    >>> a1.next()
    ('/root',
     ['.subversion', '.ssh', '.ipython', '.pki', '.cache'],
     ['test.py',
      '.bash_history',
      '.cshrc',
      '.bash_logout',
      '.tcshrc',
      '.bash_profile',
      '.mysql_history',
      '.bashrc',
      '.viminfo'])
    返回一个元组,由(文件名,[文件夹],[文件]) 组成

2. os 모듈의 경로 모듈

1) 파일 경로와 관련됨

    basename()      路径基名
    dirname()       路径目录名
    join()          整合文件名
    split()         返回dirname(),basename()元组
    splitext()      返回(filename,extension)元组
    
    例:
    >>> dir1 = os.path.dirname('/etc/sysconfig/iptables-config')
    >>> dir1
    '/etc/sysconfig'
    >>> file1 = os.path.basename('/etc/sysconfig/iptables-config')
    >>> file1
    'iptables-config'
    >>> os.path.join(dir1,file1)
     '/etc/sysconfig/iptables-config'
    >>> for filename in os.listdir('/tmp'):
            print os.path.join('/tmp',filename)

2) 정보

    getatime()      返回文件最近一次访问时间
    getmtime()      返回文件最近一次修改时间
    getctime()      返回文件最近一次改变时间
    getsize()       返回文件的大小

3) 쿼리

    exists()        判断指定文件是否存在    isabs()         判断指定的路径是否为绝对路径
    isdir()         是否为目录
    isfile()        是否为文件
    islink()        是否符号链接
    ismount()       是否为挂载点
    sanefile(f1,f2) 两个路径是否指向了同一个文件
    
    例:判断文件是否存在,存在则打开,让用户通过键盘反复输入多行数据,追加保存至此文件中
    >>> import os 
    >>> import os.path
    >>> if os.path.isfile('/tmp/s'):
            f1 = open('/tmp/s','a+')
        while True:
            a2 = raw_input("Input >> ")
            if a2 == 'q' or a2 == 'quit' :
                break
            f1.write(a2+'\n')
        f1.close()

4) 객체 영구 저장소

    把变量从内存中变成可存储或传输的过程称之为序列化
    pickle、marshal、DBM接口、shelve模块
    
    pickle   将内存对象持久存储在文件中
    >>> import pickle
    >>> dict1 = {'x':1,'y':2,'z':'hello world'}
    >>> f1 = open('/tmp/s','a+')
    >>> pickle.dump(dict1,f1)           通过流逝化将字典保存在文件中
    >>> f1.close()
    # file /tmp/s
    /tmp/s: ASCII text
    # cat /tmp/s
    (dp0
    S'y'
    p1
    I2
    sS'x'
    p2
    I1
    sS'z'
    p3
    S'hello world'
    p4
    s.
    >>> f2 = open('/tmp/s','a+')
    >>> dict2 = pickle.load(f2)         重新装载
    >>> dict2
    {'x':1,'y':2,'z':'hello world'}

위 내용은 Python의 os 모듈의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.