导入模块:

importos

显示操作系统类型:

os.name

posix



显示系统详细信息:

os.uname()

posix.uname_result(sysname='Linux',nodename='18205c3de5e0',release='3.13.0-32-generic',version='#57-UbuntuSMPTueJul1503:51:08UTC2014',machine='x86_64')


显示环境变量:

os.environ

environ({'VERSIONER_PYTHON_PREFER_32_BIT':'no','TERM_PROGRAM_VERSION':'326','LOGNAME':'michael','USER':'michael','PATH':'/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/mysql/bin',...})


获取某个环境变量的值:

os.environ.get('PATH')

'/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/mysql/bin'


查看当前目录的绝对路径:

os.path.abspath('.')

/


整合目录路径,只是把路径接起来看看,没有真正创建出来:

os.path.join('/home/q/Documents/Temp/IO','NW')

q@s:~/Documents/Temp/IO$pythonjoin.py/home/s/Documents/Temp/IO/NWq@s:~/Documents/Temp/IO$lsa.txtdir.pyfile.pyjoin.pystringio.py


真正创建目录:

os.mkdir('/home/q/Documents/Temp/IO/NW')

q@s:~/Documents/Temp/IO$pythonjoin.pyNoneq@s:~/Documents/Temp/IO$lsa.txtdir.pyfile.pyjoin.pyNWstringio.py


删除目录:

os.rmdir('/home/q/Documents/Temp/IO/NW')

q@s:~/Documents/Temp/IO$pythonjoin.pyNoneq@s:~/Documents/Temp/IO$lsa.txtdir.pyfile.pyjoin.pystringio.py




1.利用os模块编写一个能实现dir -l输出的程序。

#!/usr/bin/python#-*-coding:utf-8-*-fromdatetimeimportdatetimeimportospwd=os.path.abspath('.')print('SizeLastModifiedName')print('------------------------------------------------------------')forfinos.listdir(pwd):fsize=os.path.getsize(f)mtime=datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d%H:%M')flag='/'ifos.path.isdir(f)else''print('%10d%s%s%s'%(fsize,mtime,f,flag))

运行结果:

SizeLastModifiedName------------------------------------------------------------4692018-07-2318:25dir.py7692018-07-2317:48file.py1862018-07-2318:14stringio.py112018-07-2317:31a.txt122882018-07-2318:25.dir.py.swp