导入模块:
import os
显示操作系统类型:
os.name
posix
显示系统详细信息:
os.uname()
posix.uname_result(sysname='Linux', nodename='18205c3de5e0', release='3.13.0-32-generic', version='#57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014', 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')
[email protected]:~/Documents/Temp/IO$ python join.py /home/s/Documents/Temp/IO/NW [email protected]:~/Documents/Temp/IO$ ls a.txt dir.py file.py join.py stringio.py
真正创建目录:
os.mkdir('/home/q/Documents/Temp/IO/NW')
[email protected]:~/Documents/Temp/IO$ python join.py None [email protected]:~/Documents/Temp/IO$ ls a.txt dir.py file.py join.py NW stringio.py
删除目录:
os.rmdir('/home/q/Documents/Temp/IO/NW')
[email protected]:~/Documents/Temp/IO$ python join.py None [email protected]:~/Documents/Temp/IO$ ls a.txt dir.py file.py join.py stringio.py
1.利用os模块编写一个能实现dir -l输出的程序。
#!/usr/bin/python # -*- coding: utf-8 -*- from datetime import datetime import os pwd = os.path.abspath('.') print(' Size Last Modified Name') print('------------------------------------------------------------') for f in os.listdir(pwd): fsize = os.path.getsize(f) mtime = datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d %H:%M') flag = '/' if os.path.isdir(f) else '' print('%10d %s %s%s' % (fsize, mtime, f, flag))
运行结果:
Size Last Modified Name ------------------------------------------------------------ 469 2018-07-23 18:25 dir.py 769 2018-07-23 17:48 file.py 186 2018-07-23 18:14 stringio.py 11 2018-07-23 17:31 a.txt 12288 2018-07-23 18:25 .dir.py.swp
原文地址:http://blog.51cto.com/13502993/2149173
时间: 2024-10-12 03:39:47