• python 003 os模块 example


    import os
    for tmpdir in ('/tmp',r'C:/Users/Administrator/PycharmProjects/'):
        if os.path.isdir(tmpdir):
            break
    else:
        print 'No temp directory available'
        tmpdir = ''
    
    if tmpdir:
        os.chdir(tmpdir)
        cwd = os.getcwd()
        print '*** current temporary directory'
        print cwd
    
        print '*** creating example directory'
        while os.path.exists('example'):
            break
        else:
            os.mkdir('example')
        os.chdir('example')
        cwd = os.getcwd()
        print '*** new working directory'
        print cwd
        print '*** original directory listing:'
        print os.listdir(cwd)
        print '*** creating test file...'
        fobj = open('test','w')
        fobj.write('foo
    ')
        fobj.write('bar
    ')
        fobj.close()
        print '*** updated directory listing:'
        print os.listdir(cwd)
        print '***renaming "test" fo "filetest.txt"'
        os.rename('test','filetest.txt')
        print '***full file pathname'
        path = os.path.join(cwd,os.listdir (cwd)[0])
        print path
        print '***(pathname,basename) =='
        print os.path.split(path)
        print '***(filename,extension) =='
        print os.path.splitext(os.path.basename(path))
    
        print '***displaying file contents:'
        fobj = open(path)
        for eachLine in fobj:
            print eachLine
        fobj.close()
    
        print '***deleting test file'
        os.remove(path)
        print '***updated directory listing:'
        print os.listdir(cwd)
        os.chdir(os.pardir)
        print '*** deleting test directory'
        os.rmdir('example')
        print '*** DONE'

    输出

    C:Python27python.exe C:/Users/Administrator/PycharmProjects/untitled/ospathex.py
    *** current temporary directory
    C:UsersAdministratorPycharmProjects
    *** creating example directory
    *** new working directory
    C:UsersAdministratorPycharmProjectsexample
    *** original directory listing:
    []
    *** creating test file...
    *** updated directory listing:
    ['test']
    ***renaming "test" fo "filetest.txt"
    ***full file pathname
    C:UsersAdministratorPycharmProjectsexamplefiletest.txt
    ***(pathname,basename) ==
    ('C:\Users\Administrator\PycharmProjects\example', 'filetest.txt')
    ***(filename,extension) ==
    ('filetest', '.txt')
    ***displaying file contents:
    foo
    
    bar
    
    ***deleting test file
    ***updated directory listing:
    []
    *** deleting test directory
    *** DONE

  • 相关阅读:
    05 | 深入浅出索引(下)
    04 | 深入浅出索引(上)
    03 | 事务隔离:为什么你改了我还看不见?
    02 | 日志系统:一条SQL更新语句是如何执行的?
    01 | 基础架构:一条SQL查询语句是如何执行的?
    orm的惰性机制
    简易的迁移
    rails 中 preload、includes、Eager load、Joins 的区别
    换种方式去分页
    Scala function programming
  • 原文地址:https://www.cnblogs.com/EWWE/p/6985438.html
Copyright © 2020-2023  润新知