第四章 5 os模块 AND sys模块详解

os模块提供了很多允许你的程序与操作系统直接交互的功能

得到当前工作目录,即当前python脚本工作的路径:os.getcwd()
返回指定目录下的所有文件的目录名:os.listdir()
函数用来删除一个文件:os.remove()
删除多个目录:os.removedirs(r"c:\python")
检验给出的路径是否为同一个文件:os.path.isfile()
检验给出的路径是否为同一个目录:os.path.isdir()
检验是否是绝对路径:os.path.isabs()
检验给出的路径是否真的存在:os.path.exists()
返回一个路径的目录名和文件名:os.path.split() 
e.g  os.path.split('/home/swaroop/byte/code/poem.txt')
分离拓展名:os.splitext() e.g  os.splitext('/user/local/test.py')
获取路径名:ospath.dirname()
获取绝对路径:os.path.abspath()
获取文件名:os.path.basename()
允许shell命令:os.system()
读取操作系统环境变量HOME的值:os.getenv('HOME')
返回操作系统所有的环境变量:os.environ
设置系统环境变量,仅程序运行时有效:os.eniron.sedefault('HOME','/HOME/alex')
给出当前平台使用的终止符:os.linesep  windows使用'\r\n' linux使用'\n'
指示你正在使用的平台:os。name 对于windows 而言是'nt',而Linux|Unix 是'posix'
重命名:os.rename(old,new)
创建多级目录:os.makedirs(r'c:\python\test')
创建单个目录:os.mkdir('test')
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmd(file)
终止当前进程:os.exit()
获取当前文件大小:os.path.getsize(filename)
结合目录名与文件名: os.path.join(dir,filename)
改变工作目录到dirname:os.chdir(dirname)
获取当前终端的大小:os.get_terminal_size()
杀死进程:os.kill(10884,signal,SIGKILL)

sys模块讲解
sys.argv, 第一个元素返回此py本身的路径,返回list类型。一般结合着后接参数一起使用。
sys.exit(n),退出程序,正常退出时exit(0),一般用在逻辑判断分支上。
sys.version,获取python解释程序的版本信息
sys.maxsize,最大int值
sys.path,返回模块的搜索路径,初始化时使用PythonPath环境变量的值
sys.platform,返回操作系统平台名称,win(x64)–>win32
sys.stout.write(‘please:’),sys的标准输出

>>> import sys
>>> sys.version
'3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]'
>>> sys.maxint
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'sys' has no attribute 'maxint'
>>>
>>> sys.maxsize()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
>>> sys.maxsize
9223372036854775807
>>> sys.path
['', 'E:\\Python37\\python37.zip', 'E:\\Python37\\DLLs', 'E:\\Python37\\lib', 'E:\\Python37', 'E:\\Python37\\lib\\site-packages']
>>> sys.platform
'win32'
>>> sys.stdout
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
>>> sys.stdout.write('hey')
hey3
>>> sys.stdout.write('hey3')
hey34
>>> sys.stdout.read
<built-in method read of _io.TextIOWrapper object at 0x000002290105A630>
>>>
>>> sysy.stdout.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sysy' is not defined
>>> sys.stdout.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: not readable
>>>
>>> sys.stdout.readline()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: not readable
>>>
>>> sys.stdin.readline()

'\n'
>>> sys.getrecursionlimit()
1000
>>> sys.getdefaultcoding()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'sys' has no attribute 'getdefaultcoding'
>>> sys.getfilesystemencoding()
'utf-8'
>>>

猜你喜欢

转载自blog.csdn.net/qq_42936973/article/details/82177312