python——操作系统(os)

版权声明:©2004 Microsoft Corporation. All rights reserved. https://blog.csdn.net/qq_42036824/article/details/86601349

操作系统(os)

import os
from os.path import exists,splitext,join
1.返回操作系统类型
值为:posix,是linux系统,如果是nt,是windows系统
print(os.name)

2.操作系统的详细信息
info = os.uname()
print(info)
print(info.sysname)
print(info.nodename)

3.系统环境变量
print(os.environ)

4.通过key值获取环境变量对应的value值
print(os.environ.get('PATH'))

5.判断是否为绝对路径
print(os.path.isabs('/tmp/hello'))  ##带/的是绝对路径,否则不是
print(os.path.isabs('hello'))

6.生成绝对路径
print(os.path.abspath('hello.png'))
print(os.path.join('/home/kiosk','hello.png'))

7.获取目录名或文件名
filename = '/home/kiosk/day08/hello.png'
##获取路径中的文件名
print(os.path.basename(filename))   ##文件名为:hello.png
##获取路径中的目录名
print(os.path.dirname(filename))    ##目录名为:/home/kiosk/day08

8.创建目录/删除目录
os.mkdir('img')
os.makedirs('img/file') #创建递归目录
os.rmdir('img')

9.创建文件/删除文件
os.mknod('westos.txt')
os.remove('westos.txt')

10.文件重命名
os.rename('westos.txt','data.txt')    ##重命名为date

11.判断文件或者目录是否存在
print(os.path.exists('data.txt'))

12.分离后缀名和文件名
print(os.path.splitext('data.txt'))

('data', '.txt')
13.将目录名和文件名分离
print(os.path.split('/tmp/hello/hello.png'))

('/tmp/hello', 'hello.png')
  • 遍历目录的方法:
import os                                    
from os.path import join                     
                                             
for root,dir,files in os.walk('/var/log'):   
    # print(root)                            
    # print(dir)                             
    # print(files)                           
    for name in files:                       
        print(join(root,name))  

猜你喜欢

转载自blog.csdn.net/qq_42036824/article/details/86601349